spring @Configration扩展使用一例

最近对注解了解的比较多, 也在实际项目中实战了一把, 同时对spring中关于一些注解的源代码看了看, 下面是实际应用中对@ContextConfiguration的一些扩展
经过查看spring的源代码, 可以知道@ContextConfiguration在默认情况下是使用ClassPath的方式来加载locations指定的bean xml配置文件, 也就是说配置文件必须放在classpath路径下, 但是有些情况下, 我们需要通过相对文件路径来加载配置文件, 这个就需要自己动手来定制一番, 还好spring在这一点还是留有一定的扩展余地. 这里需要定义两个类, 一个是继承XmlBeanDefinitionReader, 然后在复写的loadBeanDefinitions方法中, 将配置文件路径包装成FileSystemResource类:
public class FileSystemXmlBeanDefinitionReader extends XmlBeanDefinitionReader {

public FileSystemXmlBeanDefinitionReader(BeanDefinitionRegistry registry) {
super(registry);
}

@SuppressWarnings("unchecked")
@Override
public int loadBeanDefinitions(String location, Set actualResources)
throws BeanDefinitionStoreException {
ResourceLoader resourceLoader = getResourceLoader();
if (resourceLoader == null) {
throw new BeanDefinitionStoreException(
"Cannot import bean definitions from location [" + location
+ "]: no ResourceLoader available");
}

Resource resource = new FileSystemResource(location);
int loadCount = loadBeanDefinitions(resource);
if (actualResources != null) {
Assert.isNull(actualResources);
}
if (logger.isDebugEnabled()) {
logger.debug("Loaded " + loadCount
+ " bean definitions from location pattern [" + location
+ "]");
}
return loadCount;

}
}

接下来就是从GenericXmlContextLoader继承, 并复写modifyLocations方法, 将配置文件路径转换成绝对路径, 另外还需要将前面的FileSystemXmlBeanDefinitionReader类作为配置文件的reader, 即可:
public class FileSystemXmlContextLoader extends GenericXmlContextLoader {
@Override
protected String[] modifyLocations(Class<?> clazz, String... locations) {
String[] modifiedLocations = new String[locations.length];
for (int i = 0; i < locations.length; i++) {
String path = locations[i];
if (path != null && path.startsWith("/")) {
path = path.substring(1);
}
modifiedLocations[i] = new File(path).getAbsolutePath();
}
return modifiedLocations;
}

@Override
protected BeanDefinitionReader createBeanDefinitionReader(
GenericApplicationContext context) {
return new FileSystemXmlBeanDefinitionReader(context);
}
}

然后在@ContextConfiguration注解中指定我们写的loader即可, 即loader = FileSystemXmlContextLoader.class
比如说, 我的一个@ContextConfiguration这样写:
@ContextConfiguration(locations = {
"/src/test/resources/spring-xx-dependency.xml",
"/src/test/resources/spring-xx-config.xml",
"/src/test/resources/spring-xx-jdbc.xml",
"/../xxx/src/main/webconfig/spring-xx-tx.xml",
"/../xxx/src/main/webconfig/spring-xx-service.xml",
"/src/test/resources/spring-xx-dao.xml" }, loader = FileSystemXmlContextLoader.class)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值