此代码在jdk11上测试通过,SpringBoot版本为2.7.14
1.上代码
public class Dome04Application {
public static void main(String[] args) {
// 这是一个干净的容器
GenericApplicationContext context = new GenericApplicationContext();
// 添加3哥Bean
context.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,销毁时执行@PreDestroy
context.registerBean(CommonAnnotationBeanPostProcessor.class);
// 注册@ConfigurationProperties注解的Bean
ConfigurationPropertiesBindingPostProcessor.register(context.getDefaultListableBeanFactory());
// 初始化
context.refresh();
// 销毁
context.close();
}
}
2.创建Bean1
public class Bean1 {
private static final Logger log = LoggerFactory.getLogger(Bean1.class);
private Bean2 bean2;
@Autowired
public void setBean2(Bean2 bean2) {
log.debug("@Autowired 生效: {}", bean2);
this.bean2 = bean2;
}
@Autowired
private Bean3 bean3;
@Resource
public void setBean3(Bean3 bean3) {
log.debug("@Resource 生效: {}", bean3);
this.bean3 = bean3;
}
private String home;
@Autowired
public void setHome(@Value("${JAVA_HOME}") String home) {
log.debug("@Value 生效: {}", home);
this.home = home;
}
@PostConstruct
public void init() {
log.debug("@PostConstruct 生效");
}
@PreDestroy
public void destroy() {
log.debug("@PreDestroy 生效");
}
@Override
public 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;
}
@Override
public String toString() {
return "Bean4{" +
"home='" + home + ''' +
", version='" + version + ''' +
'}';
}
}
2.测试结果
原文地址:https://blog.csdn.net/weixin_44702984/article/details/134826566
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如若转载,请注明出处:http://www.7code.cn/show_48836.html
如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除!
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。