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)

你可能感兴趣的:(DAO,spring,bean,xml,jdbc)