TreeviewCopyright @doctording all right reserved, powered by aleen42

@Bean注解

测试程序

@Configuration
public class AppConfig {

    @Bean(initMethod = "init")
    public UserManager userManager(){
        UserManager userManager = new UserManager("wangwu");
        userManager.setUserName("zhangsan");
        return userManager;
    }
}
public class UserManager {
    String userName;

    public UserManager() {
        System.out.println("constructor UserManager():" + userName);
    }

    public UserManager(String userName) {
        this.userName = userName;
        System.out.println("constructor UserManager(String):" + userName);
    }

    public void init() {
        System.out.println("start init UserManager:" + userName);
    }


    @Override
    public String toString() {
    return "UserManager{" +
        "userName='" + userName + '\'' +
        '}';
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }
}
  • 测试
AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(AppConfig.class);
UserManager userManager = (UserManager) ac.getBean("userManager");
System.out.println(userManager);

输出:

constructor UserManager(String):wangwu
start init UserManager:zhangsan
UserManager{userName='zhangsan'}

源码流程

  • 1 new AnnotationConfigApplicationContext的时候会初始化添加一个ConfigurationClassPostProcessor

  • 2 当执行ConfigurationClassPostProcessorpostProcessBeanDefinitionRegistry方法时会找到全注解类,手动注册全注解类的bean,其时一个cglib代理实现,同时会执行读取器中的@Bean注解,完成userManagerBeanDefinition的注册

  • 3 refresh方法走到finishBeanFactoryInitialization(beanFactory);doCreateBean("userManager")时,会走到实例化UserManager

具体时配置类AppConfig的代理实现类的方法反射执行的@Bean注解里面的代码逻辑

  • 4 最后是bean生命周期方法了

Copyright @doctording all right reserved,powered by Gitbook该文件修改时间: 2022-05-29 08:36:13

results matching ""

    No results matching ""