@Configuration 配置類注解
聲明一個類是配置類,等同于配置檔案中的
applicationcontext.xml
。
加載Spring配置的兩種方式:
- ClassPathXmlApplicationContext XML方式
ApplicationContext app = new ClassPathXmlApplicationContext("applicationcontext.xml");
- AnnoatationConfigApplicationContext 注解方式
ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
@ComponentScan 包掃描注解
@ComponentScan(value="com.enjoy.cap2")表示掃描此目錄下的包。
參數說明:
- value:指定要掃描的包
- excludeFilters = Filter[]:指定掃描的時候按照什麼規則排除那些元件
- includeFilters = Filter[]:指定掃描的時候隻需要包含哪些元件
- useDefaultFilters = false:預設是true,掃描所有元件,要改成false,includeFilters 和excludeFilters才會生效
掃描規則如下:
- FilterType.ANNOTATION:按照注解
- FilterType.ASSIGNABLE_TYPE:按照給定的類型;比如按BookService類型
- FilterType.ASPECTJ:使用ASPECTJ表達式
- FilterType.REGEX:使用正則指定
- FilterType.CUSTOM:使用自定義規則,自已寫類,實作TypeFilter接口
示例:
/**
* 包掃描測試類
*
* @author yuhao.wang3
* @since 2019/8/24 10:39
*/
@Configuration
@ComponentScan(value = "com.xiaolyuh.component.scan", includeFilters = {
// 隻掃描Controller注解的 Bean
@ComponentScan.Filter(type = FilterType.ANNOTATION, classes = {Controller.class}),
// 隻掃描特定的類
@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, classes = {TestService.class}),
// 使用特定的過濾規則
@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {CustomTypeFilter.class})
}, useDefaultFilters = false)
public class ComponentScanConfig {
}
@Test
public void contextTest() {
String[] names = context.getBeanDefinitionNames();
Arrays.stream(names).forEach(System.out::println);
}
輸出結果:
componentScanConfig
testController
customTypeFilter
customTypeFilterService
testService
TestDao就沒有被加載,完整代碼請到倉庫拉取
@Bean 聲明一個Bean,并放到Spring容器
将一個普通類聲明成一個Spring裡面的Bean。等同于XML中的
<bean id="xxx" class="xxx"/>
。Spring bean 的初始化和銷毀的三種方式和執行順序 可參考這裡。
@Scope 描述的是Spring容器如何建立Bean的執行個體的
- singleton:一個Spring容器中隻有一個Bean的執行個體,以為Spring的預設配置,全容器共享一個執行個體,在容器初始化的時候,完成Bean的初始化。
- prototype:每次調用建立一個Bean的執行個體。在容器初始化的時候也會存一個沒有初始化的Bean标示到容器。
- request:Web項目中,給每一個HTTP request建立一個Bean的執行個體。
- session:Web項目中,給每一個HTTP session建立一個Bean的執行個體。
示例:
@Configuration
public class ScopeConfig {
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Bean("scopeTestBean")
public ScopeTestBean scopeTestBean() {
return new ScopeTestBean();
}
}
@Lazy
在 Spring 單例模式下,預設在容器初始化的時候建立Bean,如果加了@Lazy注解,那麼容器啟動的時候不會去執行個體化對象,而是在第一次使用Bean的時候才回去建立對象。
示例:
@Configuration
public class LazyConfig {
@Lazy
@Bean
public LazyTestBean lazyTestBean() {
return new LazyTestBean();
}
}
Spring 聲明Bean的注解
- @Component: 元件,沒有明确的角色。
- @Service : 在業務邏輯層(Service層)使用。
- @Repository: 再資料通路層(Dao層)使用。
- @Controller: 再展現層(MVC->Spring MVC)使用。
Spring 注入Bean的注解:
- @Autowired:Spring提供的注解。
- @inject:JSR-330提供的注解。
- @Resource:JSP-250提供的注解。
聲明Spring Bean和注入Bean的幾種常用注解和差別可參考這裡。
@Conditional 條件注入
當引入@Conditional時, 容器可以選擇性的注冊bean。具體可以參考:Spring 條件注解(@Conditional)。
@Import注冊bean
@Import
注解一次可以注入多個Bean,預設使用全類名作為Bean id;而
@Bean
一次隻能注入一個Bean,預設使用方法名作為Bean id。
詳情可參考:聲明Spring Bean和注入Bean的幾種常用注解和差別
源碼
https://github.com/wyh-spring-ecosystem-student/spring-boot-student/tree/releases