今天一个小伙伴问我,在一个listener里面注入serices没法获取到实例,是因为他没有被spring容器加载注入
所以,想要services对象,不能使用@Resouces 来注入了,后来采用了applicationcontext来操作获取到,废话不多少,直接上代码
1、新增一个类:
package com.daolong.sharebook.util;
/**
* @author dengjihai
* @create 2017-11-15
**/
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
/**
* @author dengjh
* @create 2017-11-15
**/
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String beanName) {
return applicationContext.getBean(beanName);
}
public static Object getBean(Class c) {
return applicationContext.getBean(c);
}
}
2、调用获取services:
ApplicationContext appCtx = SpringContextUtil.getApplicationContext();
SdStoreInfoService service = appCtx.getBean(SdStoreInfoService.class);
3、perfect!
22 篇文章
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!