在Spring MVC中,Controller中使用service只需使用注解@Resource/@Autowired就行,但是一般类(即不使用@Controller注解的类)要用到service时,Spring中的Service不是你想new就能new的,因为通过new实例化的对象脱离了Spring容器的管理,获取不到注解的属性值,所以会是null,就算调用service的类中有@Component注解加入了Spring容器管理,也还是null.
一、普通类与工具类共同的解决方法:
这里的普通类指的:是不在spring容器管理下的类,是通过new 来实例化的类。
1、SpringContextUtil
package com.fh.interceptor;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* Created by 小胡 on 2020/6/17.
*/
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
// 下面的这个方法上加了@Override注解,原因是继承ApplicationContextAware接口是必须实现的方法
@Override
public void setApplicationContext(ApplicationContext applicationContext)
throws BeansExceptio
3446




被折叠的 条评论
为什么被折叠?



