javascript
Spring学习(七)bean装配详解之 【通过注解装配 Bean】【自动装配的歧义解决】...
本文借鑒:Spring學習,@Bean 的用法(特此感謝!)
自動裝配
1、歧義性
我們知道用@Autowired可以對bean進行注入(按照type注入),但如果有兩個相同類型的bean在IOC容器中注冊了,要怎么去區分對哪一個Bean進行注入呢?
如下情況,若用@Autowired的方式按類型注入,IOC容器就不知道應該注入哪個了:
<bean name="source1" class="pojo.Source"><property name="fruit" value="橙子"/><property name="sugar" value="多糖"/><property name="size" value="超大杯"/> </bean> <bean name="source2" class="pojo.Source"><property name="fruit" value="橙子"/><property name="sugar" value="少糖"/><property name="size" value="小杯"/> </bean>Spring對這種情況提供了2個注解進行解決:
@Primary 注解
定義:代表首要的,當 Spring IoC 檢測到有多個相同類型的 Bean 資源的時候,會優先注入使用該注解的類。
問題:該注解只是解決了首要的問題,但是并沒有選擇性的問題。
@Qualifier 注解
定義:此注解可以讓Spring使用name的方式進行Bean的裝配以及注入
/* 包名和import */ public class JuiceMaker {......@Autowired@Qualifier("source1")//指定注入名稱為 "source1" 的 Bean 資源public void setSource(Source source) {this.source = source;} }2、使用@Bean 裝配 Bean
基礎用法
定義:@Bean是一個方法級別上的注解,主要用在@Configuration注解的類里,也可以用在@Component注解的類里。
用法:標識這個方法可以產生一個Bean并且交給Spring容器管理,告訴Spring可以在這個方法中拿到一個Bean。
PS:添加的bean的id為方法名
@Configuration public class AppConfig {@Bean//用@Bean注解配置Bean時,bean的ID默認為方法的名稱public TransferService transferService() {return new TransferServiceImpl();}}上面的代碼等同于
<beans><bean id="transferService" class="com.acme.TransferServiceImpl"/> </beans>bean的依賴
@bean 也可以依賴其他任意數量的bean,如果TransferService 依賴 AccountRepository,我們可以通過方法參數實現這個依賴。
@Configuration public class AppConfig {@Beanpublic TransferService transferService(AccountRepository accountRepository) {//PS:此方法的入參就是返回值所依賴的對象return new TransferServiceImpl(accountRepository);}}3、Bean的作用域
可以通過 @Scope 注解或者 <bean> 元素中的 scope 屬性來設置Bean的作用域
4、Spring 表達式
一個例子簡單了解下:?
package pojo;import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component;@Component("elBean") public class ElBean {// 通過 beanName 獲取 bean,然后注入role這個對象@Value("#{role}")private Role role;// 獲取 bean 的屬性 id,并注入給id這個變量@Value("#{role.id}")private Long id;// 調用 bean 的 getNote 方法,并注入給note這個變量@Value("#{role.getNote().toString()}")private String note;/* getter and setter */ }小結:?
@Value("#{}") 表示SpEl表達式,通常用來獲取bean的屬性,或者調用bean的某個方法,或者常量注入。
PS:簡要的說,就是通過@Value這個注解注入對象或者屬性給相應的變量(簡單的理解為賦值操作)。
?
?
轉載于:https://www.cnblogs.com/riches/p/11526413.html
總結
以上是生活随笔為你收集整理的Spring学习(七)bean装配详解之 【通过注解装配 Bean】【自动装配的歧义解决】...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Node.Js同步mongdb数据
- 下一篇: 文件处理与路径