1、基本裝配
1.0 屬性注入和構(gòu)造器注入的差異
- 屬性注入直白易懂,缺點是對于屬性可選的時候,很多個構(gòu)造函數(shù)會顯得類很臃腫。
- 構(gòu)造注入是一種高內(nèi)聚的體現(xiàn),特別是針對有些屬性需要在對象在創(chuàng)建時候賦值,且后續(xù)不允許修改(不提供setter方法)。
1.1
@Component注解:表明該類會作為組件類,spring為其創(chuàng)建bean,參數(shù)為id(也可使用@Named注解為bean設(shè)置ID)
@ComponentScan:默認(rèn)不啟用組件掃描,需要顯示配置,默認(rèn)掃描與配置類相同的包,參數(shù)為包的名稱,
- 可以設(shè)置基礎(chǔ)包:
@ComponentScan(basePackage={"soundsystem", "video"}) - 可以指定包中含的類或接口:
@ComponentScan(basePackageClassess={CDPlayer.class, DVDPlayer.class})
若使用xml啟動組件掃描:<context:component-scan base-package="soundsystem" />
1.2
@Bean(destoryMethod="shutdown")
@Autowired:spring特有,可用@Inject替換,自動裝配,可用在構(gòu)造器或?qū)傩缘腟etter方法上,參數(shù)required=true時,沒有匹配到bean會拋異常,
1.3 JavaConfig - 通過Java裝配bean
- 給類添加
@Configuration注解 - @Bean注解方法,創(chuàng)建所需實例,id與方法名一致,屬性name可指定
- 裝配有依賴的bean:
return new CDPlayer(sgtPeppers()); //sgtPeppers方法也被注解bean,需要在同一個配置類中
public CDPlayer cdPlyaer(CompactDisc compactDisc) //自動裝配CompactDisc到方法中,降低關(guān)聯(lián)
1.4 XML裝配bean
- 創(chuàng)建xml文件,并以
<beans>為根 <bean id='名字' class='類的全名' />-
<constructor-arg ref="引用的bean的id">或者 c-命名空間模式xmlns:c="http://www.springframework.org/schema/c" bean id="cdPlayer" class="" c:cd-ref="引用id" /> - 使用
<constructor-arg>元素進(jìn)行構(gòu)造器參數(shù)的注入 || 使用c:_title或者c:_0進(jìn)行參數(shù)的注入
1.5 屬性設(shè)置
對強(qiáng)依賴使用構(gòu)造器注入
對可選性依賴使用屬性注入
spring的p-命名空間替代<property>元素:xmlns:p="https://www.springframework.org/schema/p" p:compactDisc-ref="compactDisc //裝配compactDisc屬性
c-命名空間和p-命名空間:-ref后綴是裝配bean,沒有裝配的就是字面量,不能使用p-空間裝配集合,
1.6 組合配置
拆分config
- @Import導(dǎo)入config
- 創(chuàng)建更高級別的config,然后組合
@Import({a.class, b.class}) - javaconfig加載xml
@ImportResource("classpath:xx-config.xml") - xml中引用javaconfig
<bean class="xx.config /> //使用xml配置 <bean id="player" class="com.player" c:cd-ref="comDisc" /> //使用java描述
2、高級裝配
2.1 profile(環(huán)境)
- profile決定哪個bean創(chuàng)建和不創(chuàng)建,沒指定profile則始終都被創(chuàng)建
- 給bean或方法配置@Profile("***")注解 || 在xml的頭添加
profile="***" - 需要配置激活哪個profile(dispatcherservlet的初始化參數(shù)、web應(yīng)用的上下文參數(shù)、JNDI條目、環(huán)境變量、JVM系統(tǒng)屬性、集成測試時用@ActiveProfiles注解)
- 配置:
spring.profiles.active || spring.profiles.active
3、條件化bean
@Conditional(MagicExistsCondition.class) //條件創(chuàng)建bean public class MagicExistsCondition implements Condition { public boolean matches { return true/false; } }
ConditionContext接口:
- 檢查bean的定義(getRegistry())
- 檢查bean是否存在(getBeanFactory())
- 檢查環(huán)境變量(getEnvironment())
- 檢查資源(getResourceLoader())
- 檢查類是否存在(getClassLoader())
AnnotatedTypeMetadate接口:檢查帶有@Bean注解的方法上還有什么其他的注解(isAnnotated())
3.1.1 自動裝配有歧義時
- 標(biāo)示首選bean:@Component @Primary || @Bean @Primary || xml中primary="true"
- 限定自動裝配:@Qualifier("限定符_bean_id");
- 可以給bean設(shè)置限定符:@Qualifier("***")
3.2 bean的作用域
在bean的類上使用@Scope注解,參數(shù)為ConfigurableBeanFactory.SCOPE_XXXXX
默認(rèn)所有的bean:單例(singleton)模式
- 單例singleton:整個應(yīng)用一個bean實例
- 原型prototype:每次注入或者通過spring上下文獲取的時候都創(chuàng)建新實例
- 會話session:每個會話
- 請求request:每個請求