spring注入static属性

背景:

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

坑:

如果你使用这样的注入方式的话,都是null,注入不进去。

复制代码
@Autowired
private static TestService testService;
@Resource
private static TestService testService;
@Value("${key}")
private static String key;

解决办法

(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;      
       }  
}
(3)MethodInvokingFactoryBean

通过MethodInvokingFactoryBean工厂Bean,可以将指定方法返回值注入成为目标Bean的属性值,MethodInvokingFactoryBean用来获得指定方法的返回值,该方法可以是静态方法 也可以是实例方法。 获得的方法返回值既可以被注入到指定Bean实例的指定属性,也可以直接定义成Bean实例。
Java实体类中是这样的

复制代码
private static String decryptToken;

    public static void setDecryptToken(String decryptToken) {
        DecryptUtil.decryptToken = decryptToken;
    }

xml中是这样的

复制代码
    <bean id="configIdStatic" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
        <property name="staticMethod" value="com.....setDecryptToken"/>
        <property name="arguments" value="${decryptToken}"/>
    </bean>

如果arguments 是多个,采用 List 赋值。

复制代码
    <bean id="configIdStatic" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
	<property name="staticMethod" value="com....setDecryptToken"/>
	<property name="arguments">
		<list>
			<value>decryptToken</value>
		</list>
	</property>
	</bean>

参考:

https://segmentfault.com/a/1190000019844427utm_source=tag-newest

https://www.sojson.com/blog/157.html

https://www.cxyzjd.com/article/weixin_42608550/97675350

相关推荐
风象南1 小时前
Spring Boot实现HTTPS双向认证
java·spring boot·后端
是一个Bug1 小时前
Spring Boot 的全局异常处理器
spring boot·后端·python
嘻哈baby1 小时前
Prometheus + Grafana 监控系统搭建实战:从零到生产可用
后端
5***84641 小时前
【SpringBoot3】Spring Boot 3.0 集成 Mybatis Plus
spring boot·后端·mybatis
Java水解1 小时前
MySQL - 一文理清存储引擎:InnoDB vs MyISAM 核心差异
后端
青春不流名1 小时前
Java List初始化的例子
java·windows·list
4***17271 小时前
【MySQL篇】使用Java操作MySQL实现数据交互
java·mysql·交互
sheji34161 小时前
【开题答辩全过程】以 基于Spring Boot的流浪动物救助系统设计为例,包含答辩的问题和答案
java·spring boot·后端
今天也很困1 小时前
用户密码安全存储:Go 实现 SM3 哈希加盐
后端