@Configuration注解的詳細介紹


1.Configuration注解的介紹

用於修飾配置類,內部定義一些組件;

2.Configuration的兩種模式

3.Configuration注解的定義

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {
    @AliasFor(
        annotation = Component.class
    )
    String value() default "";

    boolean proxyBeanMethods() default true;
}

3.1由該注解定義可知

  1. 該注解首先是一個組件,所以會被@SpringBootApplication注解掃描(掃描的前提是該注解必須在與啟動類相同包或者子包中)
  2. 該注解中有一個屬性 proxyBeanMethods,該屬性的默認值是true,這個屬性可以分為兩種模式
  • Full模式(即為默認值):proxyBeanMethods = true;
  • Lite模式:proxyBeanMethods = false;

3.2Full模式與Lite模式的區別

  1. 使用Full模式,這個配置類就被代理,所以可以解決組件之間的依賴關系,正是因為可以解決,組件依賴的問題,所以他會先檢查容器中是否存在組件的實例,如果存在就會直接只用,不存在才會調用組件進行創建;
  2. 如果是Lite模式,就不會產生代理類,每次調用都會執行一次,SpringBoot會跳過在容器中查找的步驟;

3.3那么什么時候使用Full和Lite呢

  1. 當沒有組件依賴的時候就是用Lite,這樣會使程序啟動更快;
  2. 當有組件依賴的時候就是用Full,即為默認值;

3.4兩種模式使用測試

MyConfig.java

/**
 * 1、配置類里面使用@Bean標注在方法上給容器注冊組件,默認也是單實例的
 * 2、配置類本身也是組件
 * 3、proxyBeanMethods:代理bean的方法
 * Full(proxyBeanMethods = true)、【保證每個@Bean方法被調用多少次返回的組件都是單實例的】
 * Lite(proxyBeanMethods = false)【每個@Bean方法被調用多少次返回的組件都是新創建的】
 * 組件依賴必須使用Full模式默認。其他默認是否Lite模式
 */
@Configuration(proxyBeanMethods = false)//告訴SpringBoot這是一個配置類 == 配置文件
public class MyConfig {

    /**
     * Full:外部無論對配置類中的這個組件注冊方法調用多少次獲取的都是之前注冊容器中的單實例對象
     *
     * @return
     */
    @Bean//給容器中添加組件。以方法名作為組件的id。返回類型就是組件類型。返回的值,就是組件在容器中的實例
    public People people() {
        return new People(1, "遷承", dog());
    }

    @Bean
    public Dog dog() {
        return new Dog(1, "嘻嘻");
    }
}
啟動類

@SpringBootApplication
public class QianchengApplication {

    public static void main(String[] args) {
        ApplicationContext context = SpringApplication.run(QianchengApplication.class, args);
        /**
         * 使用Full模式的時候會輸出
         * com.qiancheng.config.MyConfig$$EnhancerBySpringCGLIB$$fae131c9@27aae97b
         * true
         */
        /**
         * 使用Late模式的時候輸出
         * com.qiancheng.config.MyConfig@13a37e2a
         * false
         */
        MyConfig bean = context.getBean(MyConfig.class);
        System.out.println(bean);
        People people = context.getBean("people", People.class);
        Dog dog1 = context.getBean("dog", Dog.class);
        System.out.println(people.getDog() == dog1);
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM