本文主要是介绍java每日一记 —— 常见的Bean后置处理器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
此代码在jdk11上测试通过,SpringBoot版本为2.7.14
1.上代码
1.测试方法
public class Dome04Application {public static void main(String[] args) {// 这是一个干净的容器GenericApplicationContext context = new GenericApplicationContext();// 添加3哥Beancontext.registerBean("andyBean01", Bean1.class);context.registerBean("andyBean02", Bean2.class);context.registerBean("andyBean03", Bean3.class);context.getDefaultListableBeanFactory().setAutowireCandidateResolver(new ContextAnnotationAutowireCandidateResolver());// 注入解析Autowired注解的Bean// 执行时机:依赖注入context.registerBean(AutowiredAnnotationBeanPostProcessor.class);// 解析@Resource @PostConstruct @PreDestroy注解的Bean// 执行时机:依赖注入解析@Resource,初始化前执行@PostConstruct,销毁时执行@PreDestroycontext.registerBean(CommonAnnotationBeanPostProcessor.class);// 注册@ConfigurationProperties注解的BeanConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());// 初始化context.refresh();// 销毁context.close();}
}
2.创建Bean1
public class Bean1 {private static final Logger log = LoggerFactory.getLogger(Bean1.class);private Bean2 bean2;@Autowiredpublic void setBean2(Bean2 bean2) {log.debug("@Autowired 生效: {}", bean2);this.bean2 = bean2;}@Autowiredprivate Bean3 bean3;@Resourcepublic void setBean3(Bean3 bean3) {log.debug("@Resource 生效: {}", bean3);this.bean3 = bean3;}private String home;@Autowiredpublic void setHome(@Value("${JAVA_HOME}") String home) {log.debug("@Value 生效: {}", home);this.home = home;}@PostConstructpublic void init() {log.debug("@PostConstruct 生效");}@PreDestroypublic void destroy() {log.debug("@PreDestroy 生效");}@Overridepublic String toString() {return "Bean1{" +"bean2=" + bean2 +", bean3=" + bean3 +", home='" + home + '\'' +'}';}
}
3.创建Bean2
public class Bean2 {
}
4.创建Bean3
public class Bean3 {
}
5.创建Bean4
@ConfigurationProperties(prefix = "java")
public class Bean4 {private String home;private String version;public String getHome() {return home;}public void setHome(String home) {this.home = home;}public String getVersion() {return version;}public void setVersion(String version) {this.version = version;}@Overridepublic String toString() {return "Bean4{" +"home='" + home + '\'' +", version='" + version + '\'' +'}';}
}
2.测试结果
这篇关于java每日一记 —— 常见的Bean后置处理器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!