springboot自定义包扫描路径
目标:
项目springboot-jpa需要使用项目zzc-test的controller类
解决方案:
springboot-jpa引入依赖zzc-test,并在springboot-jpa中使用spring的componentScan方法注册新的扫描包路径
项目结构
注册包路径扫描类
@Component
public class ComponentScanRegister implements BeanDefinitionRegistryPostProcessor, PriorityOrdered {
@Override
public int getOrder() {
return PriorityOrdered.LOWEST_PRECEDENCE;
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
}
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
}
}
取需要扫描的包路径,注册到spring
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) throws BeansException {
Set<String> packages =new HashSet<String>();
String configFileLocation = "META-INF/framework/component-scan-include.txt";
packages.addAll(getComponentScanList(configFileLocation));
//最终提交给 spring
if(packages!=null && packages.size()>0){
ClassPathBeanDefinitionScanner scanner =new ClassPathBeanDefinitionScanner(registry);
scanner.scan(packages.toArray(new String[]{}));
}
}读取配置文件
“META-INF/framework/component-scan-include.txt”
component-scan-include.txt:
com.demo.service.impl
com.demo.controller
private List<String> getComponentScanList(String configFileLocation) {
List<String> result =new ArrayList<String>();
URL url =null;
try {
Enumeration<URL> urls =Thread.currentThread().getContextClassLoader().getResources(configFileLocation);
if(urls!=null){
while (urls.hasMoreElements()) {
url = urls.nextElement();
Resource resource =new UrlResource(url);
if(resource!=null && resource.exists()){
List<String> readLines = IOUtils.readLines(resource.getInputStream(), "utf-8");
result.addAll(readLines);
}
}
return result;
}
} catch (IOException e) {
throw new RuntimeException("Error in configuration file : " + url,e);
}
return null;
}