Re: [問題] autowired問題一問
==============================================================================
→ qrtt1: 另外就是,你寫這個是想要達到什麼目的?看不太懂意圖 10/08 18:17
→ goldberg123: 我想先把bean inject進來,再依照需求對bean裡的屬性 10/09 12:29
→ goldberg123: 做塞值動作,所以我才會先autowired進來再去set值 10/09 12:29
→ goldberg123: 不過好像違背@autowired精神,當初考量到這樣寫是因為 10/09 12:30
→ goldberg123: 是我有一支class需要做成兩個不同的bean 10/09 12:32
→ goldberg123: 就是同一支class只是差在屬性不同 A的bean的id='A' 10/09 12:32
→ goldberg123: B的bean的id='B'這樣 10/09 12:33
==============================================================================
需求清楚了,就知道怎麼處理了,只是屬性不同但 class 是一樣的
這太常見了,像是一個專案常有一個以上的 javax.sql.DataSource 物件
http://bit.ly/2dWib5e
@ConfigurationProperties(prefix = "aSet")
@Bean
ConcreteClass aSet() {
return new ConcreteClass();
}
(bSet 也長得一樣,只是 prefix, method name 不同)
在 application.properties 內只要寫:
aSet.id=this is a set
bSet.id=this is b set
對好後,就只是不同組的 configuration 跟 prefix 罷了
http://bit.ly/2dWhFUy
@RestController
public class GreetingController {
@Autowired ConcreteClass aSet;
@Autowired ConcreteClass bSet;
@RequestMapping("/aSet")
public ConcreteClass aSet() {
return aSet;
}
@RequestMapping("/bSet")
public ConcreteClass bSet() {
return bSet;
}
}
qty:spring-prefix qrtt1$ curl -s http://127.0.0.1:8080/aSet | jq .
{
"id": "this is a set"
}
qty:spring-prefix qrtt1$ curl -s http://127.0.0.1:8080/bSet | jq .
{
"id": "this is b set"
}
這樣有沒有簡單又明白呢!?
--
JCConf 工商服務
https://www.facebook.com/jcconf/posts/974947969317750
JCConf 2016 售票至 10/9 (日) 結束呦 :D
報名網址:http://twjug.kktix.cc/events/jcconf2016-register
議程網址:http://jcconf.tw/2016/
--
※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 111.251.136.87
※ 文章網址: https://www.ptt.cc/bbs/java/M.1476006942.A.5F4.html
※ 編輯: qrtt1 (111.251.136.87), 10/09/2016 17:59:12
推
10/10 12:48, , 1F
10/10 12:48, 1F
→
10/10 12:48, , 2F
10/10 12:48, 2F
推
10/10 14:50, , 3F
10/10 14:50, 3F
討論串 (同標題文章)
完整討論串 (本文為第 2 之 2 篇):
0
36
java 近期熱門文章
PTT數位生活區 即時熱門文章
14
23