温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

spring中怎么实现静态注入

发布时间:2021-06-21 18:16:04 来源:亿速云 阅读:274 作者:Leah 栏目:大数据

本篇文章为大家展示了spring中怎么实现静态注入,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

spring实现静态注入(类或者属性)

场景是:工具类一般都是静态方法,静态方法只能访问静态属性。所以,我们需要静态注入类或者属性。

常规操作:

注入类或者方法:

@Autowired
private TestService testService;
[@Resource](https://my.oschina.net/u/929718)
private TestService testService;
@Value("${key}")
private String key;

这样,我们就把容器里的类和Enviroment里的值注进去了。

静态注入操作:

我们使用相同的方式进行注入

@Autowired
private static TestService testService;
[@Resource](https://my.oschina.net/u/929718)
private static TestService testService;
@Value("${key}")
private static String key;

我们在静态方法使用的时候,会出现null; 发现注入不进去。

解决办法有两种方式: (1)@PostConstruct方式实现

@Component  
public class TestUtil {
   @Autowired	
   private static TestService testService;
   private static TestUtil testUtils;
      
   @PostConstruct      
   public void init() {          
      testUtils =this;          
      testUtils.testService =this.testService;      
   }  
}

@PostConstruct 注解的方法在加载类的构造函数之后执行,也就是在加载了构造函数之后,执行init方法;(@PreDestroy 注解定义容器销毁之前的所做的操作)这种方式和在xml中配置 init-method和 destory-method方法差不多,定义spring 容器在初始化bean 和容器销毁之前的所做的操作;

(2)set方法注入实现

@Component  
public class TestUtil {
   	
   private static TestService testService;
   private static String key;
        @Value("{key}")
  	public void setTestService(String key) {          
  		TestUtil.key = key;      
   	}  

        @Autowired
	public void setTestService(TestService testService) {          
  		TestUtil.testService =this.testService;      
   	}  
}

上述内容就是spring中怎么实现静态注入,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注亿速云行业资讯频道。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI