亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Springboot工具類如何使用自動綁定

Springboot工具類如何使用自動綁定

至尊寶的傳說 2019-03-11 12:12:07
Springboot工具類如何使用自動綁定
查看完整描述

2 回答

?
絕地無雙

TA貢獻1946條經驗 獲得超4個贊

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;
}
}

在靜態工具類中注入Bean

public class AccountManageClient {

@Autowired
private PcodeService pcodeService; // 嘗試自動綁定Service

private static String getDepartmentPcode(String department) {
try {
List<PcodePO> pcodes = pcodeService.findAll(); // 嘗試使用自動綁定的service
for (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.添加一個該類的靜態對象作為屬性

@Autowired
private PcodeService pcodeService;

// 3. 使用@PostConstruct方法引導綁定
@PostConstruct
public 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 "";
}
}



查看完整回答
反對 回復 2019-03-20
  • 2 回答
  • 0 關注
  • 970 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號