欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

spring_注解[email protected][email protected][email protected]_ @Lazy

程序员文章站 2022-05-21 22:38:13
...

在spring2.x版本之前,spring的配置更多使用的是 xml文件的方式,操作。
在spring3.x版本之后,spring更加推荐使用 @Configuration 配置类的方式来创建对象。

前提工作

创建普通类 DemoAService

package com.by.demo;


public class DemoAService {

}

使用xml的方式创建对象在容器中

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <!--
        id:当前对象的唯一标识
        class:需要创建的对象的全路径
    -->
    <bean id="demoAService" class="com.by.demo.DemoAService"></bean>
    
</beans>

使用 @Configuration注解

创建普通类,添加 @Configuration注解,变为配置类。

package com.by.config;

import com.by.demo.DemoAService;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Created by ydd 
 */
@Configuration //表示当前类为配置类 ,代替beans.xml文件 
public class BeansConfig {
    
    /*<bean id="demoAService" class="com.by.demo.DemoAService"></bean>*/
    /*
    *   方法返回值就是需要添加在容器中的对象 。对应xml中的class
    *   方法名,就是对象名,对应id
    *   添加 @bean 注解将对象添加在容器中 
    */
    @Bean
    public DemoAService demoAService(){
        return new DemoAService();
    }
}

使用 @ComponentScan(“com.by.xxx”)

在xml文件中可以扫描注解创建对象。
被扫描的注解有:
@Controller
@Service
@Repository
@Component

<!--扫描当前包下的注解 -->
<context:component-scan base-package="com.by.demo"></context:component-scan>

在配置类中,使用 @ComponentScan(“com.by.demo”)同样可以实现效果。

@Configuration //表示当前类为配置类 ,代替beans.xml文件
@ComponentScan("com.by.demo")
public class BeansConfig {
}

@scope

xml文件:
scope说明当前对象的作用域,是单例,多例,session ,request

<bean id="demoAService" class="com.by.demo.DemoAService" scope="singleton"></bean>

@Scope

    //@Scope("prototype")
    @Scope("singleton")
    @Bean
    public DemoAService demoAService(){
        return new DemoAService();
    }

查看 @scope
@Target({ElementType.TYPE, ElementType.METHOD})

@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Scope {

说明,该注解可以添加在类和方法上。
在方法上,指定该@bean对象的作用域。
在类上,指定当前类中@bean对象的作用域。

lazy

懒加载,可以设置 为 true、false。
当作用域是 singleton 时:

  • 如果是true:创建容器的时候,并不会直接创建对象,只有在调用的时候才会创建对象。
  • 如果是false:创建容器的时候,就会直接创建对象。

xml文件 :

<bean id="demoAService" class="com.by.demo.DemoAService" 
          lazy-init="true" scope="singleton"></bean>

@lazy注解

    @Scope("singleton")
    @Lazy
    @Bean
    public DemoAService demoAService(){
        return new DemoAService();
    }