此代码在jdk11上测试通过,SpringBoot版本为2.7.14
1.上代码
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 + '\'' +
'}';
}
}