1.认识ApplicationContextAware接口
当一个类实现了这个接口之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
2.实现ApplicationContextAware接口
3.在Spring的配置文件中注册该bean
4.使用方法:直接在filter中使用即可
当一个类实现了这个接口之后,这个类就可以方便获得ApplicationContext中的所有bean。换句话说,就是这个类可以直接获取spring配置文件中,所有有引用到的bean对象。
2.实现ApplicationContextAware接口
package com.taotao.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
public class Myawer implements ApplicationContextAware {
//Spring的上下文
private static ApplicationContext applicationContext;
public static <T> T getBean(Class<T> t){
return applicationContext.getBean(t);
}
/**
* 实现ApplicationContextAware接口方法,设置上下文环境
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
this.applicationContext = applicationContext;
}
}
3.在Spring的配置文件中注册该bean
<!--配置此bean用来在filter或者servlet中获取Spring的 bean -->
<bean id="myawer" class="com.taotao.util.Myawer"/>
4.使用方法:直接在filter中使用即可
ItemService itemService = Myawer.getBean(ItemService.class);
TbItem itemById = itemService.getItemById((long) 536563);
System.out.println(itemById.getTitle());