在将spring的xml配置改为java配置的过程中,遇到了一些问题,block时间比较长的一个问题是资源(.xml, .properties)的路径找不到,最后是使用PathMatchingResourcePatternResolver解决的。

背景:Spring+MyBatis

入口:

@Configuration
@Import({
DalConfig.class
XXDBConfig.class
})
@ImportResource(locations = {"classpath*:spring/applicationContext.xml", "classpath*:spring-dao/applicationContext.xml"})
public class Config {
@Bean
public PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver(){
return new PathMatchingResourcePatternResolver();
}
}

DalConfig

@Configuration
public class DalConfig {
@Bean
public DalDataSourceFactory xxDalDataSource() {
return new DalDataSourceFactory();
} @Bean
public PropertyPlaceholderConfigurer configBean(
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver) throws IOException {
List<Resource> resources = new ArrayList<>();
resources.addAll(Arrays.asList(pathMatchingResourcePatternResolver.getResources("classpath*:config.properties")));
resources.addAll(Arrays.asList(pathMatchingResourcePatternResolver.getResources("classpath*:/META-INF/app.properties"))); PropertyPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertyPlaceholderConfigurer();
propertyPlaceholderConfigurer.setLocations(resources.toArray(new Resource[resources.size()]));
propertyPlaceholderConfigurer.setIgnoreUnresolvablePlaceholders(true);
return propertyPlaceholderConfigurer;
}
}

XXDBConfig

@Configuration
public class XXDBConfig { @Bean
public DataSource dataSourceXXXDB(
@Value("${DBDataCenter}") String dbDataCenter,
@Value("${CFX_DataSource_ServiceUrl}") String cfxDataSourceServiceUrl,
@Value("${app.id}") String appId,
DalDataSourceFactory xxxDalDataSource) throws Exception {
return xxxxDalDataSource.createDataSource(
"xxx" + dbDataCenter,
cfxDataSourceServiceUrl,
appId);
} @Bean
public SqlSessionFactoryBean sqlSessionFactoryXXXDB(
DataSource dataSourceXXXDB,
PathMatchingResourcePatternResolver pathMatchingResourcePatternResolver) throws IOException {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSourceXXXDB);
sqlSessionFactoryBean.setMapperLocations(
pathMatchingResourcePatternResolver.getResources("classpath:com/xx/xxxdb/mapper/**/*.xml") //**表示迭代查找
);
return sqlSessionFactoryBean;
} @Bean
public MapperScannerConfigurer mapperScannerConfigurerXXXDB() {
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
return mapperScannerConfigurer;
}
}

Test

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes=Config.class)
public class DBConfigTest {
@Autowired
private ApplicationContext ctx; @Autowired
private Environment env; @Test
public void checkXXXDB(){
MapperScannerConfigurer mapperScannerConfigurerXXXDB = (MapperScannerConfigurer)ctx.getBean("mapperScannerConfigurerXXXDB");
assertNotNull(mapperScannerConfigurerXXXDB); } }

由于不同db的代码在一个jar里,通过配置来实现按需初始化db连接

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Conditional(DBConfigLoadCondition.class)
public @interface DBConfigLoadConditional {
String value();
}
public class DBConfigLoadCondition implements Condition {
@Override
public boolean matches(ConditionContext context, AnnotatedTypeMetadata metadata) {
if (context.getEnvironment() != null) {
MultiValueMap<String, Object> attrs = metadata.getAllAnnotationAttributes(DBConfigLoadConditional.class.getName());
if (attrs != null) {
Properties properties = getProperties();
String strDBList = properties.getProperty("db.list");
if(strDBList != null){
String[] arrDBList = strDBList.split(",");
String condition = (String)attrs.getFirst("value");
if(condition == null){
return true;
}
for(String db : arrDBList){
if(db != null && db.trim().equalsIgnoreCase(condition)){
return true;
}
}
}
}
} return false;
} private Properties getProperties() {
Properties pro = new Properties();
try{
pro.load(DBConfigLoadCondition.class.getResourceAsStream("/META-INF/app.properties"));
}catch (IOException ex){
ex.printStackTrace();
}
return pro;
}
}

Spring混合配置时,遇到配置文件路径NotFound,使用PathMatchingResourcePatternResolver解决的更多相关文章

  1. Spring和junit测试之配置文件路径

    本人在测试一个方法时需要加载XML配置文件,spring提供了相应的方法,就小小研究了下,在此记录下具体的过程,方便初学者和自己日后回顾. Spring容器最基本的接口就是BeanFactory. B ...

  2. spring 通过启动命令配置文件路径

    公司使用dubbo开发,提供了很多的服务,每个服务中一些配置都是一样的,比如注册中心地址,公共码表库等一下配置,这样在部署每一个程序的时候,修改每一个服务的配置增加很多的工作量.且领导不想对程序有大的 ...

  3. 三大框架SSH(struts2+spring+hibernate)整合时相关配置文件的模板

    最近在学SSH三大框架的整合,在此对他们整合时相关配置文件做一简单的模板总结,方便以后复用! 首先是web.xml配置文件,这里面就配置一些简单的监听器.过滤器,包括spring核心配置文件appli ...

  4. Spring——ClassPathXmlApplicationContext(配置文件路径解析 1)

    ClassPathXmlApplicationContext     在我的 BeanFactory 容器文章中主要提及了 BeanFactory 容器初始化(Spring 配置文件加载(还没解析)) ...

  5. spring结合时,web.xml的配置

    <!-- 1. web.xml配置 <context-param> <param-name>webAppRootKey</param-name> <pa ...

  6. java spring 等启动项目时的异常 或 程序异常的解决思路

    今天搭建ssm项目的时候,因为pagehelper的一个jar包没有导入idea的web项目下的lib目录中,异常报错找不到pagehelper,这个问题在出异常的时候疯狂crash,让人心情十分不舒 ...

  7. springboot查找配置文件路径的过程

    spring加载配置文件是通过listener监视器实现的,在springboot启动时: 在容器启动完成后会广播一个SpringApplicationEvent事件,而SpringApplicati ...

  8. 使用Spring加载properties配置文件.md

    背景 类似于datasource.properties之类的配置文件,最初通过Java的Properties类进行处理.这种方式有许多弊端,如每次都需要读取配置文件:若将Properties作为成员变 ...

  9. ssh整合思想初步 struts2与Spring的整合 struts2-spring-plugin-2.3.4.1.jar下载地址 自动加载Spring中的XML配置文件 Struts2下载地址

    首先需要JAR包 Spring整合Structs2的JAR包 struts2-spring-plugin-2.3.4.1.jar 下载地址 链接: https://pan.baidu.com/s/1o ...

随机推荐

  1. 【C#】CLR内存那点事(初级)

    最近回头看了一下书,对内存的理解又有新的认识.我所关注的内存里面说没有寄存器的,所以我关注的只有 托管堆(heap),栈(stack), 字符串常量池(string是一个很特殊的对象) 首先我们看两个 ...

  2. CString::MakeLower Crash

    记录一下使用CString::MakeLower可能导致的crash的一个问题: 问题重现: int _tmain(int argc, _TCHAR* argv[]){ std::string  sT ...

  3. 关于使用idea的一些小技巧

    1:idea与git同步以后查看修改变化: file --setting--versioncontorller

  4. C#在线运行--cmd方法

       此次C#在线运行采用cmd.exe用csc对文件进行编译,然后再运行的思路实现在线运行的效果.不过会生成二个文件(.cs和.exe),可能需要定期清除临时文件夹. 首先利用时间戳生成唯一文件名, ...

  5. OC字符串与C语言字符串之间的相互转换

    1.C转OC字符串 const char *cString = "This is a C string"; // 动态方法 NSString *ocString1 = [[NSSt ...

  6. CI框架部署后访问出现404

    昨天新配置了一个PHP集成开发环境,安装完后,把项目放到Apache服务器的www目录下,发现只能打开首页,其他页面全部无法打开,当时比较纳闷,以为是服务器没有配置好,测试了一下,发现环境配置没有问题 ...

  7. 如何用python批量翻译文本?

    首先,看一下百度翻译的官方api文档. http://api.fanyi.baidu.com/api/trans/product/apidoc # coding=utf-8 #authority:bi ...

  8. 错误代码: 1142 REFERENCES command denied to user 'wuyong'@'localhost' for table 'orders'

    错误代码: 1142 REFERENCES command denied to user 'wuyong'@'localhost' for table 'orders' 原因:在使用SQLyog操作数 ...

  9. 解决vs code中golang插件依赖安装失败问题

    解决vs code中golang插件依赖安装失败问题 Installing github.com/nsf/gocode SUCCEEDED Installing github.com/uudashr/ ...

  10. netstat查看tcp连接的状态

    netstat -n | awk '/^tcp/ {++state[$NF]} END {for(key in state) print key,"\t",state[key]}'