在项目中经常遇见需要在Listener中或者工具中使用Spring容器中的bean实例,由于bean不能在stataic的类中使用. 介绍一种方式: public class SpringTool { public static Object getObjectFromApplication(HttpSession session,String beanName){ ServletContext servletContext= session.getServletContext(); //通过W…
正好以前项目中碰到这个问题,现在网上偶然又看到这个问题的博文,那就转一下吧. 原文:http://blog.lifw.org/post/46428852 感谢作者 另外补充下:在web Server容器中,无论是Servlet,Filter,还是Listener都不是Spring容器管理的,因此我们都无法在这些类中直接使用Spring注解的方式来注入我们需要的对象,当然除了下面我们详细说的方法外,还有的比如说为了在Servlet中使用Spring容器的对象,那么可以参考如下两篇文章: <Serv…
在使用spring容器的web应用中,业务对象间的依赖关系都可以用context.xml文件来配置,并且由spring容器来负责依赖对象 的创建.如果要在servlet中使用spring容器管理业务对象,通常需要使用WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext())来获得WebApplicationContext,然后调用WebApplicationContext.getBean("be…
spring提供了一系列的*Aware 接口,用于获取相应的对象,进行一系列的对象设置操作,此处实现ApplicationContextAware来获取ApplicationContext. 其他Aware接口有: BeanNameAware 获得到容器中Bean的名称 BeanFactoryAware 获得当前bean Factory,从而调用容器的服务 ApplicationContextAware 当前的application context从而调用容器的服务 MessageSourceA…
@Bean(autowire = Autowire.BY_NAME,value = "kaptchaProducer") public Producer kaptchaProducer() { Properties kaptchaProperties = new Properties(); kaptchaProperties.put("kaptcha.border", "no"); kaptchaProperties.put("kapt…
1.有时候在项目中需要定时启动某个任务,对于这个需求,基于JavaEE规范,我们可以使用Listener与TimerTask来实现,代码如下: public class TestTaskListener implements ServletContextListener { //Context()初始化方法 @Override public void contextInitialized(ServletContextEvent sce) { //新建一个定时管理器 new TestTimerMa…
7.5 Spring容器中的Bean 7.5.1 Bean的基本定义和Bean别名 <beans.../>元素是Spring配置文件的根元素,该元素可以指定如下属性: default-lazy-init : 指定该<beans.../> 元素下配置的所有Bean默认的延迟初始化行为. default-merge : 指定该<beans.../> 元素下配置的所有Bean默认的merge行为. default-autowire : 指定该<beans.../>…
7.4 使用 Spring 容器 Spring 有两个核心接口:BeanFactory 和 ApplicationContext,其中ApplicationContext 是 BeanFactory 的子接口.它们都可代表 Spring 容器,Spring 容器是生成 Bean 实例的工厂,并管理容器中的Bean. Java 程序面向接口编程,无须关心 Bean 实例的实现类:但 Spring 容器负责创建 Bean 实例,因此必须精确知道每个 Bean 实例的实现类,故Spring 配置文件必…
在使用Spring做IoC容器的时候,有的类不方便直接注入bean,需要手动获得一个类型的bean. 因此,实现一个获得bean实例的工具类,就很有必要. 以前,写了一个根据bean的名称和类型获取bean实例的2个工具方法,发现每次调用后,都需要强制转换成目标结果类型. 这样很不方便,突然想到可以使用Java泛型方法,实现1个新的工具方法,避免了类型转换. import org.springframework.beans.BeansException; import org.springfra…
上一篇我们讲了SpringBoot中Tomcat的启动过程,本篇我们接着讲在SpringBoot中如何向Tomcat中添加Servlet.Filter.Listener 自定义Servlet.Filter.Listener Spring容器中声明ServletRegistrationBean.FilterRegistrationBean.ServletListenerRegistrationBean @Bean public ServletRegistrationBean customServl…