问题:
要对一个公共模块项目,进行一个拆分,做一个细化。调整的时候,调整了启单类的位置(并未注意到),单元测试的时候,就报错。
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
SpringUtils.applicationContext = applicationContext;
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return applicationContext.getBean(name);
}
public static <T> T getBean(Class<T> requiredType) {
return applicationContext.getBean(requiredType);
}
}
setApplicationContext 调试的时候,方法没进去。说明bean没有初始化。
处理1: 检查目录
启动类要在顶层的位置,这样才会读整个,就不用设置@ComponentScan
处理2:设置@ComponentScan
指定具体读取的路径
@ComponentScan(basePackages = {"com.basic.common"})
public class BasicCommonApplication {
public static void main(String[] args) {
SpringApplication.run(BasicCommonApplication.class, args);
}
@Bean
public DozerBeanMapperFactoryBean dozerBeanMapperFactoryBean() {
return new DozerBeanMapperFactoryBean();
}
}
总结:
如果在单个项目中,启动类需要在顶层的位置,才不用设置@ComponentScan,否则需要进行设置,才能读取得到。