本文转自:
https://blog.youkuaiyun.com/w_wensan/article/details/79238169
https://blog.youkuaiyun.com/songsongmianbao/article/details/60956129
使用SpringMVC框架,在开发的过程中有一些工具类、静态非controller类需要调用由spring管理的service层。但是使用@Autowired注解注入Service,会报null异常,通过new在工具类中实例化引入对象时,虽然当前引入对象不再报空指针,但是与引入对象关联的其他对象仍然会报null异常,为此在网上查到如下解决办法:
1、在配置文件(springmvc.xml)中加入工具类所在包的扫描配置。
2、改造工具类,代码如下:
@Component // 这里需将工具类声明为spring组件,这个必须不能忘
public class TestUtils {
@Autowired
private ItemService itemService;
@Autowired
// private ItemMapper itemMapper;
// 静态初使化当前类
private static TestUtils testUtils;
// 在方法上加上注解@PostConstruct,这样方法就会在Bean初始化之后被Spring容器执行(注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。
@PostConstruct
public void init() {
testUtils = this;
}
// utils工具类中使用service或mapper接口的方法例子,用"testUtils.xxx.方法" 就可以了
public static void test(Item record) {
// 调用service的方法
testUtils.itemService.insert(record);
}
}
好了,以上就是我的改造过程~我在自己的项目中测试通过了。
还有一些其他的方法,这边也记录下,不过没有测试。觉得不太符合springmvc的使用习惯啊:
//applicationContext-service.xml为声明service的配置文件名
ApplicationContext ac = new ClassPathXmlApplicationContext(“applicationContext-service.xml”);
//”userService”为配置文件中定义的service的ID,
UserService uService = (UserService) ac.getBean(“userService”);
第二种写法会重新读取配置文件,不建议使用