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 小时前
Django
后端·python·django
天河归来2 小时前
第三方接口不稳定,如何让核心任务继续完成
java·大数据
Knight_AL3 小时前
Java 文件下载时文件名中的 `#` 被转换成 `%23`?一次 URL 编码与解码问题排查
java·开发语言
利威尔xu3 小时前
Go IM 源码实战(14):本地缓存快 3000 倍,失效却难 10 倍
后端·缓存·微服务·面试·golang
逃逸线LOF4 小时前
Ribbon负载均衡原理(Irule组件、源码分析)
后端·spring cloud·ribbon
砚底藏山河4 小时前
python量化自定义周期 K 线合成
java·开发语言·数据库·python·金融
慢云智慧空间4 小时前
从设备智能到空间理解,空间智能终端解决方案商如何重新定义行业标准
后端
利威尔xu4 小时前
Go IM 源码实战(13):30 个会话只有 2 个红点,未读数错在三条路径
redis·后端·微服务·面试·golang
猿究院_夏燊5 小时前
MySQL 的四种隔离级别
java·数据库·mysql
薛定谔的猫-菜鸟程序员5 小时前
软件架构设计师开发资料大全(从入门到精通)
后端·python·系统架构·flask·架构设计师