在线观看不卡亚洲电影_亚洲妓女99综合网_91青青青亚洲娱乐在线观看_日韩无码高清综合久久

鍍金池/ 問答/Java/ SpringBoot:請教@PostConstruct為什么會被執(zhí)行兩次

SpringBoot:請教@PostConstruct為什么會被執(zhí)行兩次

圖片描述

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修飾的方法會被執(zhí)行兩次

訪問http://localhost:8080/連續(xù)輸出
Creating Boss.
Creating Boss.

回答
編輯回答
詆毀你

@Configuration會創(chuàng)建一個Bean實(shí)例;
@Bean會再創(chuàng)建一個Bean實(shí)例;
所以就導(dǎo)致創(chuàng)建了兩個對象,故@PostConstruct被執(zhí)行了兩次。

2017年5月2日 05:16