1. 程式人生 > >多執行緒Spring注入失敗

多執行緒Spring注入失敗

    在對Spring進行測試(多執行緒環境)時發現ExpertBlogService一直注入失敗,後來發現多執行緒環境下Spring是不會對新執行緒進行管理的,所以需要我們手動載入配置檔案,另外將載入部分部分放進靜態塊中防止多次載入,程式碼如下:

    private static ApplicationContext ctx = null;

    private static ExpertBlogService expertBlogService;

    private static ExpertBlogMapper expertBlogMapper;

    //When you use @Autowired in a new thread,you will get a nullpointerException
    static {
        ctx = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
        expertBlogMapper = (ExpertBlogMapper) ctx.getBean("expertBlogMapper");
        expertBlogService = new ExpertBlogServiceImpl(expertBlogMapper);
    }