問題
spring boot中咱們經常會在configuration類中經過@Bean註解去聲明Bean。
可是不少人不清楚默認狀況下,經過@Bean註解聲明的Bean的名稱是什麼?java
請問,以下代碼聲明bean的名稱是什麼?web
@Configuration
public class LogAutoConfigure {
@Bean
public Queue queueTest() {
return new Queue("log-queue", true);
}
}
爲何咱們要關注聲明bean的名稱,這是因爲spring容器中的bean默認是單例模式的,若是聲明的bean的名稱同樣,就沒法識別出具體調用哪個。在調用的時候就會出錯。spring
The bean 'queueTest', defined in class path resource [com/hcf/base/log/config/LogDataSourceConfig.class], could not be registered. A bean with that name has already been defined in class path resource
試驗
@Configuration
public class LogConfigure {
@Bean(name="queue-test")
public Queue queue() {
return new Queue("log-queue1", true);
}
@Bean
public Queue queueTest() {
return new Queue("log-queue2", true);
}
}
使用單元測試去獲取spring容器中的baensql
@Component
public class ApplicationContextHelper implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public ApplicationContextHelper() {
}
/**
* 實現ApplicationContextAware接口的回調方法,設置上下文環境
* @param applicationContext
* @throws BeansException
*/
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
ApplicationContextHelper.applicationContext = applicationContext;
}
/**
* 得到spring上下文
* @return
*/
public ApplicationContext getApplicationContext() {
return applicationContext;
}
public Object getBean(String beanName) {
return applicationContext != null ? applicationContext.getBean(beanName) : null;
}
}
@SpringBootTest(classes = LogApplication.class)
class LogApplicationTests {
@Autowired
ApplicationContextHelper contextHelper;
@Test
void testGetBean(){
Queue queue1 = (Queue) contextHelper.getBean("queue-test");
System.out.println(queue1);
Queue queue2 = (Queue) contextHelper.getBean("queueTest");
System.out.println(queue2);
}
}
執行單元測試的結果:微信
Queue [name=log-queue1, durable=true, autoDelete=false, exclusive=false, arguments={}, actualName=log-queue1]
Queue [name=log-queue2, durable=true, autoDelete=false, exclusive=false, arguments={}, actualName=log-queue2]
結論
經過觀察咱們不難發現,默認狀況下,使用 @Bean聲明一個bean,bean的名稱由方法名決定。此外,能夠經過@Bean註解裏面的name屬性主動設置bean的名稱。app
注入指定名稱的bean
@Autowired
@Qualifier("queue-test")
private Queue queue;
典型場景
多數據源配置場景:
每一個數據源都使用setDataSource()方法配置數據源,因此要使用@Bean(name = "j3sqlDataSource")中經過name主動說明bean的名字
ide
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
消息隊列中,多隊列聲明
這裏經過採用不一樣的方法名,聲明多個隊列和交換器,避免bean的名稱重複
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
![在這裏插入圖片描述](http://static.javashuo.com/static/loading.gif)
總結
一、spring boot中經過@Bean聲明bean,默認狀況下,bean的名稱由方法名決定。另外,能夠經過@Bean註解裏面的name屬性主動設置bean的名稱。
二、經過@Autowired和@Qualifier("queue-test")結合使用,能夠注入指定名稱的bean單元測試
更多精彩,關注我吧。
測試
![圖注:跟着老萬學java](http://static.javashuo.com/static/loading.gif)
本文分享自微信公衆號 - 跟着老萬學java(douzhe_2019)。
若有侵權,請聯繫 support@oschina.cn 刪除。
本文參與「OSC源創計劃」,歡迎正在閱讀的你也加入,一塊兒分享。spa