web工程非Spring管理的Bean使用Spring管理的Bean

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qincidong/article/details/82781754

某个类的属性在每次构建对象时传入,且属性不是固定的,就没法使用spring管理它。但这个类有可能应用其他被spring管理的类。

那么既然是web工程,我们可以创建一个ServletContextListener,然后在web.xml中配置该监听器即可。

public class InitDataListener implements ServletContextListener {  
      
    @Override  
    public void contextDestroyed(ServletContextEvent event) {  
        
    }  
  
    @Override  
    public void contextInitialized(ServletContextEvent event) {  
        ApplicationContext context = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
		SpringUtil.setContext(context);
    }  
}  

SpringUtil:

public class SpringUtil {
    private static ApplicationContext context;
    public static void setContext(ApplicationContext _context) {
	    context = _context;
    }
    public static Object getBean(String beanName) {		
        if (context != null) {
            return context.getBean(beanName);
        } else {
            return null;
        }
    }
    public static <T> T getBean(Class<T> tClass) {
        if (context != null) {
            return context.getBean(tClass);
        }
        return null;
    }
}

web.xml:

<listener>
    <listener-class>com.tommy.myapp.listener.InitDataListener</listener-class>
</listener>

然后其他工程中可以通过SpringUtil.getBean()来获取spring管理的bean。

当然了,你用一个Servlet也是可以的,继承HttpServlet,在init()中获取ApplicationContext,注意在web.xml中配置该servlet。

这里可能的应用场景包括:
1.在系统启动时查询一些数据放入内存等等;–也可以使用@PostConstruct注解,在对象初始化后执行。
2.在非Spring管理的类中应用Spring管理的类。

猜你喜欢

转载自blog.csdn.net/qincidong/article/details/82781754