ConfigurationClassPostProcessor 之 @ComponentScan
java
package com.github.mengweijin.mybatisplus.demo.ComponentScan.test;
import lombok.Data;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@Data
@Component
@ComponentScan(value = "com.github.mengweijin.mybatisplus.demo.ComponentScan.entity")
public class ComponentScanConfiguration {
}
java
package com.github.mengweijin.mybatisplus.demo.ComponentScan.entity;
import org.springframework.stereotype.Component;
@Component
public class ComponentScanEntity {
}
测试
虽然测试类扫描的是 ComponentScan.test 包下的所有类,并没有扫描 ComponentScan.entity 包。 但由于 ComponentScanConfiguration 类上添加了注解 @ComponentScan(value = "com.github.mengweijin.mybatisplus.demo.ComponentScan.entity")
因此,ComponentScan.entity 包下面的 ComponentScanEntity 也能够被 Spring 容器扫描到,这就是 @ComponentScan 的用法。
java
package com.github.mengweijin.mybatisplus.demo.ComponentScan.test;
import com.github.mengweijin.mybatisplus.demo.ComponentScan.entity.ComponentScanEntity;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
@Slf4j
public class TestComponentScan {
@Test
public void componentScan(){
String basePackages = "com.github.mengweijin.mybatisplus.demo.ComponentScan.test";
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(basePackages);
Assertions.assertNotNull(context.getBean(ComponentScanEntity.class));
context.close();
}
}