Spring MVC中普通类调用service

  • Post author:
  • Post category:其他


在Spring MVC中,Controller中使用service只需使用注解@Resource就行,但是一般类(即不使用@Controller注解的类)要用到service时,可查看下述方法:


原因:

Spring中的Service不是你想new就能new的,因为通过new实例化的对象脱离了Spring容器的管理,获取不到注解的属性值,所以会是null,就算调用service的类中有@Component注解加入了Spring容器管理,也还是null.


大致总结出来

就是要先建立一个工具类SpringUtil,这个工具类实现了接口ApplicationContextAware ,然后在代码里写上application的get set方法,方便我们去获取我们想要的bean

1、SpringApplicationContext

@Component
public class SpringApplicationContext implements ApplicationContextAware {

	private static ApplicationContext applicationContext;

	private SpringApplicationContext() {
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		SpringApplicationContext.applicationContext = applicationContext;
	}

	public static <T> T getBean(String name, Class<T> requiredType) {
		return applicationContext.getBean(name, requiredType);
	}

	public static <T> T getBean(Class<T> requiredType) {
		return applicationContext.getBean(requiredType);
	}

	public static ApplicationContext getContext() {
		return applicationContext;
	}

	public static Environment getEnvironment() {
		return applicationContext.getEnvironment();
	}

}

2、Spring的配置文件application.xml中进行如下配置

<bean id="SpringApplicationContext" class="com.test.framework.utils.SpringApplicationContext" scope="singleton"></bean>

3、使用

DictService dictService = (DictService) SpringContextUtil.getBean("dictService");
List<dict> dict = (List<dict>) dictService.findByHQL(hql);

参考文章:


https://blog.csdn.net/wqc19920906/article/details/80009929


https://www.cnblogs.com/chen-lhx/p/5410717.html



版权声明:本文为wslzjr原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。