Spring注解開發@Bean和@ComponentScan使用案例
組件注冊
用@Bean來注冊
搭建好maven web工程
pom加入spring-context,spring-core等核心依賴
創建實例類com.hjj.bean.Person, 生成getter,setter方法
public class Person { private String name; private int age;}
創建com.hjj.config.MainConfig
@Configuration //告訴spring是一個配置類public class MainConfig { // 給容器中注冊一個Bean,類行為返回值的類型,id默認是用方法名作為id @Bean('mikePerson') public Person person(){ return new Person('mike',20); }}
主測試類
public class MainTest { public static void main(String[] args) { AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); Person bean = applicationContext.getBean(Person.class); System.out.println(bean); String[] beanNamesForType = applicationContext.getBeanNamesForType(Person.class); for (String type : beanNamesForType) { System.out.println(type); //配置類中的方法名,注意:通過修改配置類的@bean value也可以修改 } }}
@ComponentScan包掃描
配置類中MainConfig.java
@Configuration //告訴spring是一個配置類@ComponentScan('com.hjj') // 掃描包的路徑public class MainConfig { // 給容器中注冊一個Bean,類行為返回值的類型,id默認是用方法名作為id @Bean('mikePerson') public Person person(){ return new Person('mike',20); }}
新建測試的com.hjj.controller,service,dao
@Controllerpublic class BookController {}@Repositorypublic class BookDao {}@Servicepublic class BookService {}
單元測試
@Test public void test01(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); //獲取所有組件 for (String beanDefinitionName : beanDefinitionNames) { System.out.println(beanDefinitionName); } }
ComponentScan字段,有includeFilter(),和excludeFilter() 只包含或排除某些組件
@ComponentScan(value = 'com.hjj',excludeFilters={@Filter(type=FilterType.ANNOTATION,classes={Controller.class,Service.class})})@ComponentScan(value = 'com.hjj',includeFilters={@Filter(type=FilterType.ANNOTATION,classes={Controller.class,Service.class})},userDefaultFilters=false)
// excludeFilter源碼ComponentScan.Filter[] excludeFilters() default {};
// ComponentScan.Filter源碼@Retention(RetentionPolicy.RUNTIME)@Target({})public @interface Filter { FilterType type() default FilterType.ANNOTATION; @AliasFor('classes') Class<?>[] value() default {}; @AliasFor('value') Class<?>[] classes() default {}; String[] pattern() default {};}
@ComponentScan被@Repeatable(ComponentScans.class),可以重復寫,用來寫不同的執行策略。
@ComponentScans 里面可以放ComponentScan類型的值
@Retention(RetentionPolicy.RUNTIME)@Target({ElementType.TYPE})@Documentedpublic @interface ComponentScans { ComponentScan[] value();}
FilterType
public enum FilterType { ANNOTATION, // 按注解掃描 ASSIGNABLE_TYPE, // 按給定的類型 ASPECTJ, // 可以用aspectJ表達式 REGEX, // 正則表達式 CUSTOM; // 自定義規則 private FilterType() { }}
ASSIGNABLE_TYPE
@ComponentScan(value = 'com.hjj',includeFilters ={@ComponentScan.Filter(type=FilterType.ASSIGNABLE_TYPE,classes = {BookService.class})})// config配置如上注解后 bookservice,可以被發現 @Test public void demoTest1(){ AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class); String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames(); for (String beanDefinitionName : beanDefinitionNames) { System.out.println(beanDefinitionName); } }
Custom 可以自定義配置或寫業務掃描類的信息,match返回true則是加到組件
1.復寫TypeFilter的match方法
public class MyTypeFilter implements TypeFilter { /** * * @param metadataReader 讀取到的當前正在掃描的類的信息 * @param metadataReaderFactory 可以獲取到其他任何類信息 * @return * @throws IOException */ @Override public boolean match(MetadataReader metadataReader, MetadataReaderFactory metadataReaderFactory) throws IOException { // 獲取當前類注解的信息 AnnotationMetadata annotationMetadata = metadataReader.getAnnotationMetadata(); // 獲取當前正在掃描類的信息 ClassMetadata classMetadata = metadataReader.getClassMetadata(); // 獲取當前類資源(類的路徑等) Resource resource = metadataReader.getResource(); String className = classMetadata.getClassName(); System.out.println('className:' + className); return false; }}
2. 加上注解
@Configuration //告訴spring是一個配置類@ComponentScan(value = 'com.hjj',includeFilters ={ @ComponentScan.Filter(type=FilterType.CUSTOM,classes = {MyTypeFilter.class})}, useDefaultFilter=false)public class MainConfig {}@Testpublic void test01(){AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();for (String beanDefinitionName : beanDefinitionNames) {System.out.println(beanDefinitionName);}}
結果
className:com.hjj.test.IOCTestclassName:com.hjj.MainTestclassName:com.hjj.bean.PersonclassName:com.hjj.config.MyTypeFilterclassName:com.hjj.demo.DemoTestclassName:com.hjj.demo.EmployeeclassName:com.hjj.demo.Managerorg.springframework.context.annotation.internalConfigurationAnnotationProcessororg.springframework.context.annotation.internalAutowiredAnnotationProcessororg.springframework.context.annotation.internalCommonAnnotationProcessororg.springframework.context.event.internalEventListenerProcessororg.springframework.context.event.internalEventListenerFactorymainConfig
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持好吧啦網。
相關文章:
