Spring通过@Configuration和@Bean注解方式创建bean解析

有三个类TestA、TestB、TestConfig

TestA
@Getter
@Setter
public class TestA {
}
TestB
@Getter
@Setter
public class TestB {
    private TestA testA;
}
TestConfig
@Configuration
public class TestConfig {

    @Bean("testaa")
    public TestA testA() {
        return new TestA();
    }
    @Bean
    public TestB testB() {
        TestB testB = new TestB();
        testB.setTestA(testA());
        return testB;
    }

    public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(TestConfig.class);
        TestA testA = applicationContext.getBean(TestA.class);
        TestB testB = applicationContext.getBean(TestB.class);
        TestA testaa = (TestA)applicationContext.getBean("testaa");
        System.out.println(testA == testaa);
        System.out.println(testA == testB.getTestA());
    }
}
main方法执行结果
true
true
Debug结果

Spring通过@Configuration和@Bean注解方式创建bean解析_第1张图片

总结
  1. @Configuration注解标记的类相当于之前的配置文件;
  2. @Bean相当于bean标签,其中类型为返回值的类型,id默认用方法名作为id,也可以在@Bean注解后面标注id名;
  3. 类中对@Bean方法的调用是通过CGLIB代理的,因此返回bean的缓存版本(不创建新的版本)。

你可能感兴趣的:(java,spring)