当前位置:   article > 正文

springboot 中 在静态方法中使用 @Autowired或者@Resource注入的对象_@resource修饰的方法怎么改成static的

@resource修饰的方法怎么改成static的

问题:像我们一般使用 spring 注入的对象时,一般都是在 public 下进行调用,现在需要在一个 static 静态方法中调用注入的对象

先上实现代码

@Component
public class InterfaceMethod {

    @Autowired
    ITInterfaceNumberService itInterfaceNumberService;


    private static ITInterfaceNumberService interfaceNumberService;

    @PostConstruct
    public void init() {
        interfaceNumberService = itInterfaceNumberService;
    }


public static void  interfaceNumberCount(){

       List<TInterfaceNumber> list = interfaceNumberService.list();
    }

}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21

实现原理如下:

1、类名上使用 @Component 使当前类成为一个bean对象,加入 spring 的管理中。(或者使用 @service)

2、先将需要调用的对象注入进来

3:重新创建一个同对象的 static 变量

4:写个 @PostConstruct 注解的方法,在这个方法里,初始化在第3步创建的 static 变量,将之前注入的对象赋值给它。

关于 @PostConstruct
@PostConstruct注解的方法在项目启动的时候执行这个方法,也可以理解为在spring容器启动的时候执行,可作为一些数据的常规化加载,比如数据字典之类的。
被@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器调用一次,修饰的方法会在构造函数之后,init()方法之前运行。

执行顺序:Constructor >> @Autowired >> @PostConstruct

需要注意的是,注解会多多少少地影响到服务器的启动速度。服务器在启动时候会遍历Web 应用的WEB-INF/classes下的所有class文件与WEB-INF/lib下的所有jar文件,以检查哪些类使用了注解。如果应用程序中没有 使用任何注解,可以在Web.xml中设置的metadata-complete属性为true

5:静态方法中就能够直接进行调用第3步创建的静态变量。

关注公众号查看更多资源
在这里插入图片描述
在这里插入图片描述

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Guff_9hys/article/detail/798471
推荐阅读
  

闽ICP备14008679号