8.高階裝配(二)
阿新 • • 發佈:2018-11-08
文章目錄
8.高階裝配(二)
3. 處理bean歧義性
1. 使用首選bean
-
標識為primary的bean將被使用,如果有多個bean標識為primary,這仍會有衝突
-
Bean
@Component @Primary public class Man {}
-
XML
<
2. 使用Qualifier限定符
-
限定符用於縮小bean的範圍
public interface B { } @Component public class B1 implements B { } @Component public class B2 implements B { }
@Component public class A { @Qualifier("b2") @Autowire
-
為宣告的bean建立自定義限定符
public interface B { } @Component public class B1 implements B { } @Qualifier("b2Custom") @Component public class B2 implements B { }
@Component public class A { @Qualifier("b2Custom") @Autowire private B b; }
-
自定義限定符
-
自定義一個註解,引入@Qualifier註解即可
@Target(...) @Retention(...) @Qualifier public @interface B1Anno() {} @Target(...) @Retention(...) @Qualifier public @interface B2Anno() {} public interface B { } @B1Anno @Component public class B1 implements B { } @B2Anno @Component public class B2 implements B { }
@Component public class A { @B2Anno @Autowire private B b; }
4. bean作用域
-
作用域
- 單例(Singleton)
- 原型(Prototype)
- 會話(Session), web應用
- 請求(Request), web應用
-
Java
@Scope(scopeName = WebApplicationContext.SCOPE_SESSION, proxyMode = ScopedProxyMode.INTERFACES) @Component public class ShoppingCar { }
-
Xml
<bean id="car" class="com.desmond.springlearning.scope.ShoppingCar" scope="session"> <aop:scoped-proxy proxy-target-class="true"></aop:scoped-proxy> </bean>
相當於 @Scope裡的 proxyMode作用.
5. 執行時注入
- 佔位符, ${xxx}
- Spring表示式SpEL #{xxx}