参考《Spring普通类获取并调用Spring service方法》,网址:https://blog.csdn.net/jiayi_0803/article/details/68924558
在Spring MVC中,Controller中使用service只需使用注解@Resource/@Autowired就行,但是一般类(即不使用@Controller注解的类)要用到service时,Spring中的Service通过new实例化的对象脱离了Spring容器的管理,获取不到注解的属性值,所以会是null,就算调用service的类中有@Component注解加入了Spring容器管理,也还是null.
---------------------
1、创建获取Spring的工具类SpringUtil
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
//创建获取Spring的工具类,用于Spring普通类或工具类获取并调用Spring service对象
public class SpringUtil implements ApplicationContextAware{
private static ApplicationContext appCtx;
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansException {
appCtx = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return appCtx;
}
public static Object getBean(String beanName) {
return appCtx.getBean(beanName);
}
}
2、通过用@Service("xxService")在service层声明service类
@Service("xxService")
public interface xxService {
}
注意不是impl实现类
3、通过@Resource在普通类或工具类中获取对象并调用service
@Resource
private xxService xxService;// Service接口
//用SpringUtil.getBean("xxService")的形式获取并调用service
xxService = (xxService) SpringUtil.getBean("xxService");
4、在applicationContext.xml 中声明该Spring工具类
<!-- Spring工具类 -->
<bean id = "springUtil" name="springUtil" class="com.xx.util.SpringUtil"/>