1.实现ApplicationContextAware。同时交给spring管理,这样在系统启动的时候将ApplicationContext对象赋值给我们自己定义的对象。
<bean class="com.mmall.common.ApplicationContextHelper" lazy-init="false" />
2.通过ApplicationContext上下文拿到对应的spring管理的bean。
@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static <T> T popBean(Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(clazz);
}
public static <T> T popBean(String name, Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(name, clazz);
}
}
<bean class="com.mmall.common.ApplicationContextHelper" lazy-init="false" />
2.通过ApplicationContext上下文拿到对应的spring管理的bean。
@Component("applicationContextHelper")
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public void setApplicationContext(ApplicationContext context) throws BeansException {
applicationContext = context;
}
public static <T> T popBean(Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(clazz);
}
public static <T> T popBean(String name, Class<T> clazz) {
if (applicationContext == null) {
return null;
}
return applicationContext.getBean(name, clazz);
}
}