I. Overview
When we used spring before, the most commonly used component scanner cooperated with the bean tag annotation to register the bean as a whole.
xml form:
<context:component-scan base-package="" />
We configure the basic package, and spring will help us scan all the classes under the basic package. Once a class is found to be marked with four annotations, it will be registered.
[1]@Controller
[2]@Service
[3]@Component
[4]Repository
Now we use the annotation mode, and there is also a set of solutions that can replace the above configuration.
2. Complete the scanner with annotations
[1] Create test beans
@Controller public class PersonController { }
@Service public class PersonService { }
@Repository public class PersonDAO { }
[2] Create configuration class
@Configuration @ComponentScan(basePackages="com.trek.springConfig.scan") public class ScanConfig { }
[3] Create a test class
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes= {ScanConfig.class}) public class ScanTest { @Autowired private ApplicationContext context; @Test public void test() { String[] beanDefinitionNames = context.getBeanDefinitionNames(); for (String name : beanDefinitionNames) { System.out.println(name); } } }
View the running results:
scanConfig
personController
personDAO
personService
We found that we have implemented a combination of package scanners and bean tag annotations for batch registration of beans.
3. Advanced Features of Packet Scanner
When we used package scanning before, we can specify scanning components and exclude specified components.
We will modify the previous configuration class.
@Configuration @ComponentScan(basePackages = "com.trek.springConfig.scan", excludeFilters = { @Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) }) public class ScanConfig { }
We use the exclude attribute for exclusions.
Then run the test class:
scanConfig
personDAO
personService
We can find that @Controller is excluded.
We scan with the specified annotation:
@Configuration @ComponentScan(basePackages = "com.trek.springConfig.scan", includeFilters = { @Filter(type = FilterType.ANNOTATION, classes = { Controller.class }) },useDefaultFilters=false) public class ScanConfig { }
It is important to note that using the include attribute must declare that the default scanning behavior is not used.