赞
踩
问题:像我们一般使用 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、类名上使用 @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步创建的静态变量。
关注公众号查看更多资源
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。