Boss.java
@Configuration
public class Boss {
@PostConstruct
public void init() {
System.out.println("Creating Boss.");
}
@Bean
public Boss getBoss() {
return new Boss();
}
}
SampleController.java
@Controller
@EnableAutoConfiguration
public class SampleController {
@RequestMapping("/")
@ResponseBody
String home() {
@SuppressWarnings("resource")
AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(Boss.class);
return "Hello World";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(SampleController.class, args);
}
}
为何通过AnnotationConfigApplicationContext加载后@PostConstruct修饰的方法会被执行两次
访问http://localhost:8080/连续输出
Creating Boss.
Creating Boss.
@Configuration
会创建一个Bean实例;@Bean
会再创建一个Bean实例;所以就导致创建了两个对象,故
@PostConstruct
被执行了两次。