自定义项目启动初始化信息的listener报错

自定义初始化组件代码如下:

@Component
public class InitComponent implements ServletContextListener, ApplicationContextAware {

    private static ApplicationContext applicationContext;


    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        ServletContext sc = servletContextEvent.getServletContext();
        //设置博主信息
        BloggerService bloggerService = (BloggerService) applicationContext.getBean("bloggerService");   //错误处
        Blogger blogger = bloggerService.getBlogger();
        blogger.setPassword(null);
        sc.setAttribute("blogger", blogger);

    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {

    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
} 

    写这段代码并且将其配在web.xml的listener中,用意在于项目启动的时候通过监听就初始化一些信息,

    但是每次启动错误处就会报NullPoint异常,经过排查才知道:

    Spring在项目启动时扫描注解配置的Bean是有顺序的,具体顺序是ApplicationContext.xml的顺序,

    问题就出在这,当扫描到这个类时如果BloggerService还没有被扫描到,就自然会报错了。

 

 
posted @ 2018-07-29 20:08  Goxcheer  阅读(366)  评论(0编辑  收藏  举报