017 包扫描器和标记注解
生活随笔
收集整理的這篇文章主要介紹了
017 包扫描器和标记注解
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
一 .概述
在之前我們使用spring時,最常用的就是組件掃描器配合Bean標記注解整體進行Bean的注冊.
xml形式:
<context:component-scan base-package="" />我們配置基礎包,spring會幫助我們將基礎包下所有的類進行掃描,一旦發現有類被標記上了一下四個注解就會進行注冊.
[1]@Controller
[2]@Service
[3]@Component
[4]Repository
現在我們使用注解模式,同樣有一套可以替換上述配置的方案.
?二 .使用注解完成掃描器
[1] 創建測試Bean
@Controller public class PersonController {} @Service public class PersonService {} @Repository public class PersonDAO {}[2] 創建配置類
@Configuration @ComponentScan(basePackages="com.trek.springConfig.scan") public class ScanConfig {}[3]創建測試類
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {ScanConfig.class}) public class ScanTest {@Autowiredprivate ApplicationContext context;@Testpublic void test() {String[] beanDefinitionNames = context.getBeanDefinitionNames(); for (String name : beanDefinitionNames) { System.out.println(name); } } }查看運行結果:
scanConfig personController personDAO personService我們發現我們實現了包掃描器加Bean的標記注解組合進行Bean的批量注冊.
?三 .包掃描器的高級功能
在之前我們使用包掃描的時候,可以指定進行掃描組件和排除指定組件.
我們將之前的配置類進行修改.
@Configuration @ComponentScan(basePackages = "com.trek.springConfig.scan", excludeFilters = {@Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) }) public class ScanConfig {}我們使用排除屬性進行排除.
然后運行測試類:
scanConfig personDAO personService我們可以發現@Controller被排除掉了.
我們使用指定注解進行掃描:
@Configuration @ComponentScan(basePackages = "com.trek.springConfig.scan", includeFilters = {@Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) },useDefaultFilters=false) public class ScanConfig {}千萬需要注意的是,使用包含屬性一定要聲明不使用默認掃描行為.
轉載于:https://www.cnblogs.com/trekxu/p/9094864.html
總結
以上是生活随笔為你收集整理的017 包扫描器和标记注解的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: WebJars——web端静态资源的ja
- 下一篇: 【原创】分布式之redis复习精讲