绝地无双
springboot支持通过set方法实现注入,我们可以利用非静态set方法注入静态变量@Component // 需要添加Component注释才会被springboot管理public class TestUtil {@Value("${link.host}")private static String linkHost;// *核心:通过非静态set方法实现注入*@Value("${link.host}")public void setLinkHost(String linkHost) {XunTongUtil.linkHost = linkHost;}public static JSONObject getAccessToken(String appid, String secret) {String apiURL = linkHost + "/test/;String responseStr = HttpUtil.sendGet(apiURL);JSONObject json = JSONObject.fromObject(responseStr);return json.getString("access_token");return json;}}在静态工具类中注入Beanpublic class AccountManageClient {@Autowiredprivate PcodeService pcodeService; // 尝试自动绑定Serviceprivate static String getDepartmentPcode(String department) {try {List<PcodePO> pcodes = pcodeService.findAll(); // 尝试使用自动绑定的servicefor (PcodePO pcode : pcodes) {if (department.contains(pcode.getDepartment())) {return pcode.getPcode();}}} catch (Exception e) {}return "";}}需要在保留原静态的属性(@Autowired)的同时,添加一个该类的静态属性。同时声明一个返回值为void的方法,在其中将非静态属性赋值给静态属性,该方法需要使用@PostConstruct注释@Component // 1. 需要添加Component注释才会被springboot管理public class AccountManageClient {public static AccountManageClient accountManageClient; // 2.添加一个该类的静态对象作为属性@Autowiredprivate PcodeService pcodeService;// 3. 使用@PostConstruct方法引导绑定@PostConstructpublic void init() {accountManageClient = this;accountManageClient.pcodeService = this.pcodeService;}private static String getDepartmentPcode(String department) {try {List<PcodePO> pcodes = accountManageClient.pcodeService.findAll(); // 4. 使用时需要这样实现for (PcodePO pcode : pcodes) {if (department.contains(pcode.getDepartment())) {return pcode.getPcode();}}} catch (Exception e) {}return "";}}