我用的框架是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);
}
}