2 回答

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
springboot支持通過set方法實(shí)現(xiàn)注入,我們可以利用非靜態(tài)set方法注入靜態(tài)變量
@Component // 需要添加Component注釋才會(huì)被springboot管理
public class TestUtil {
@Value("${link.host}")
private static String linkHost;
// *核心:通過非靜態(tài)set方法實(shí)現(xiàn)注入*
@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;
}
}
在靜態(tài)工具類中注入Bean
public class AccountManageClient {
@Autowired
private PcodeService pcodeService; // 嘗試自動(dòng)綁定Service
private static String getDepartmentPcode(String department) {
try {
List<PcodePO> pcodes = pcodeService.findAll(); // 嘗試使用自動(dòng)綁定的service
for (PcodePO pcode : pcodes) {
if (department.contains(pcode.getDepartment())) {
return pcode.getPcode();
}
}
} catch (Exception e) {
}
return "";
}
}
需要在保留原靜態(tài)的屬性(@Autowired)的同時(shí),
添加一個(gè)該類的靜態(tài)屬性。同時(shí)聲明一個(gè)返回值為void的方法,
在其中將非靜態(tài)屬性賦值給靜態(tài)屬性,該方法需要使用@PostConstruct注釋
@Component // 1. 需要添加Component注釋才會(huì)被springboot管理
public class AccountManageClient {
public static AccountManageClient accountManageClient; // 2.添加一個(gè)該類的靜態(tài)對象作為屬性
@Autowired
private PcodeService pcodeService;
// 3. 使用@PostConstruct方法引導(dǎo)綁定
@PostConstruct
public void init() {
accountManageClient = this;
accountManageClient.pcodeService = this.pcodeService;
}
private static String getDepartmentPcode(String department) {
try {
List<PcodePO> pcodes = accountManageClient.pcodeService.findAll(); // 4. 使用時(shí)需要這樣實(shí)現(xiàn)
for (PcodePO pcode : pcodes) {
if (department.contains(pcode.getDepartment())) {
return pcode.getPcode();
}
}
} catch (Exception e) {
}
return "";
}
}
- 2 回答
- 0 關(guān)注
- 973 瀏覽
添加回答
舉報(bào)