一:IOC(控制反轉(zhuǎn))基礎(chǔ)概念
ioc的思想最核心的地方在于,資源不由使用資源的雙方管理,而由不使用資源的第三方管理,這可以帶來很多好處闲昭。
第一,資源集中管理,實(shí)現(xiàn)資源的可配置和一管理。
第二,降低了使用資源雙方的依賴程度(耦合度)亿傅。
二:Spring IOC 容器底層注解使用(基于AnnotationConfigApplicationContext舉例)
2.1)@Bean
@Configurationpublic
class MainConfig {
????@Bean
?????public Person person() {
????????return new Person();
? ? }
}
通過@Bean形式注入的話,bean默認(rèn)名稱是方法名,可以通過@Bean(value="bean的名稱")指定名稱
2.2)@CompentScan(結(jié)合@Controller@Service@Repository@Compent)
@Configuration
@ComponentScan(basePackages = {"com.testcompentscan"})
public class MainConfig {}
結(jié)合excludeFilters排除
@ComponentScan(
basePackages = {"com.testcompentscan"},
excludeFilters = {
@ComponentScan.Filter(type = FilterType.ANNOTATION,value = {Controller.class}),
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE,value = {TestService.class})
})
@ComponentScan.Filter type類型
1)注解形式的FilterType.ANNOTATION?@Controller @Service @Repository @Compent
2)指定類型的FilterType.ASSIGNABLE_TYPE TestService.class
3)aspectj類型的FilterType.ASPECTJ(不常用)
4)正則表達(dá)式的FilterType.REGEX(不常用)
5)自定義的FilterType.CUSTOM?自定義類實(shí)現(xiàn)TypeFilter接口并過濾
2.3)Bean的作用域
1)@Scope指定的作用域方法取值
a) singleton 單實(shí)例的(默認(rèn))
b) prototype 多實(shí)例的?
c) request 同一次請(qǐng)求(不常用)
d) session 同一個(gè)會(huì)話級(jí)別(不常用)
2)@Lazy可以針對(duì)單實(shí)例Bean懶加載
3)@Conditional進(jìn)行條件判斷,當(dāng)條件滿足時(shí)Spring才管理該類(SpringBoot中大量使用了該注解)
2.4)@Import導(dǎo)入組件
@Import(value = {Person.class, Car.class})
通過@Import 的ImportSeletor類實(shí)現(xiàn)組件的導(dǎo)入 (導(dǎo)入組件的id為全類名路徑)
通過@Import的 ImportBeanDefinitionRegister導(dǎo)入組件 (可以指定bean的名稱)
?通過實(shí)現(xiàn)FacotryBean接口來實(shí)現(xiàn)注冊(cè)組件
2.5)Bean的初始化方法和銷毀方法
僅單實(shí)例bean有效,多例不由Spring管理
@Bean(initMethod = "init",destroyMethod = "destroy")
通過 InitializingBean和DisposableBean 的二個(gè)接口實(shí)現(xiàn)bean的初始化以及銷毀方法
通過JSR250規(guī)范 提供的注解@PostConstruct 和@ProDestory標(biāo)注的方法
通過Spring的BeanPostProcessor的bean的后置處理器會(huì)攔截所有bean創(chuàng)建過程
?初始化方法執(zhí)行先后順序
applyBeanPostProcessorsBeforeInitialization()
invokeInitMethods{
????isInitializingBean.afterPropertiesSet
????自定義的init方法
}
applyBeanPostProcessorsAfterInitialization()
2.6)自動(dòng)裝配@AutoWired
自動(dòng)裝配首先時(shí)按照類型進(jìn)行裝配拗慨,若在IOC容器中發(fā)現(xiàn)了多個(gè)相同類型的組件娃磺,那么就按照 屬性名稱來進(jìn)行裝配,可以通過@Qualifier("屬性名")來指定
2.7)使用Spring底層組件(通過實(shí)現(xiàn)XXXAware接口)
2.8)通過@Profile注解,來根據(jù)環(huán)境來激活表示不同的Bean
切換環(huán)境的方法
a)通過運(yùn)行時(shí)jvm參數(shù)來切換 -Dspring.profiles.active=test|dev|prod
b)通過代碼的方式來激活