“
同事:我想在 静态方法中调用注入的对象,但是得到的都是 null ,有什么好办法吗?
小伟同学:好,今日我就传你一招!
”
今日安利好物:static 静态方法注入 bean
像我们一般使用 spring 注入的对象时,一般都是在 public 情况下进行调用,现在我们需要在一个 static 静态方法中调用注入的对象,怎么解决呢?请往下看
01
—
实现原理
1、类名上使用 @Component 使当前类成为一个bean对象,加入 spring 的管理中。(或者使用 @service)
2、先将需要调用的对象使用
@Autowired或者@Resource
注入进来
3:重新创建一个同对象的 static 变量
4:写个 @PostConstruct 注解的方法,在这个方法里,初始化在第3步创建的 static 变量,将之前注入的对象赋值给它。
@PostConstruct:被 @PostConstruct 注解的方法在项目启动的时候执行这个方法,也可以理解为在 spring 容器启动的时候执行,可作为一些数据的常规化加载。
被 @PostConstruct 修饰的方法会在服务器加载 Servlet 的时候运行,并且只会被服务器调用一次,修饰的方法会在构造函数之后,init() 方法之前运行。
5:静态方法中直接进行调用第3步创建的静态变量。
02
—
实现方法
@Componentpublic class InterfaceMethod { @Autowired ITInterfaceNumberService itInterfaceNumberService; private static ITInterfaceNumberService interfaceNumberService; @PostConstruct public void init() { interfaceNumberService = itInterfaceNumberService; }public static void interfaceNumberCount(){ List list = interfaceNumberService.list(); }}
注:
原来的写法:如果要调用 InterfaceMethod 这里面的方法(非静态)
我们一般会用 @Autowired 或者 @Resource 注入进去,这样我如果有多个地方要用这个类中的方法,我就得每个类里面都进行注入。
现在的写法:将 InterfaceMethod 转换成静态类,静态方法,再使用这种方法进行注入,就可以通过类名调用里面的方法了,就不用每次都进行注入操作了。
点击此处留言或查看留言