java工具类注入变量,static方法里注入static变量

 我用的框架是springboot,我要实现的是在工具类中有static方法里用到注入的变量。但是普通的那种注入,是不起作用的。

解决办法:先定义要注入的变量,并且用static修饰;然后注入一个非static修饰的同类变量;然后将非static修饰的同类变量赋值给用static修饰的同类变量,例如:

import javax.annotation.PostConstruct;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class RecieverUtil {
	private static RestTemplate restTemplate;//static修饰的同类变量
	private static String address;//static修饰的同类变量
	@Autowired
	private RestTemplate restTemplate1;//非static修饰的同类变量
	@Value("${address}")
	private String address1;//非static修饰的同类变量
	@PostConstruct
    public void init() {
		restTemplate = restTemplate1;//非static修饰的同类变量 赋值给 static 修饰的同类变量
		address = address1;//非static修饰的同类变量 赋值给 static 修饰的同类变量
    }
    public static void ceshi(int aa,String bb){
		Result<Object> result = restTemplate.getForObject(address + "ceshi/getList? 
        aa="+aa+"&bb="+bb, Result.class);
	}
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值