最近在项目中学习到,动态的加载配置文件,就从网上查阅资料,整理了一篇博客《Spring加载配置文件》,大家可以看一下。
在这里简单记录一下代码:
大家可以看到,项目中有这样3个配置文件
现在要实现的是,先加载spring-parent.xml文件,然后再加载spring-one.xml和spring-two.xml文件
package org.ygy.demo.spring.test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.ygy.demo.spring.Module;
import org.ygy.demo.spring.service.AnotherService;
import org.ygy.demo.spring.service.OneService;
public class AppTest {
public static void main(String[] args) {
//1.加载父亲上下文环境
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-parent.xml");
//2.根据参数调用子类上下文环境
Module module = new Module("core", applicationContext);
OneService oneService = module.getBeanByName("oneService");
oneService.sayOne();
oneService.sayTwo();
Module another = new Module("web" , applicationContext);
AnotherService anotherService = another.getBean(AnotherService.class);
anotherService.queryOne();
anotherService.queryTwo();
}
}
package org.ygy.demo.spring;
import java.util.Iterator;
import java.util.Map;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.google.common.base.Preconditions;
import lombok.Getter;
/**
*
* @author yuguiyang
* @description 模块类,项目中有多个模块或者子项目,可能会根据需要加载不同的配置文件
* @time 2013-9-2
* @version V1.0
*/
public final class Module {
@Getter
private ApplicationContext applicationContext;
/**
*
* @param moduleName 模块名称
* @param parentContext 父亲上下文
*/
public Module(String moduleName,ApplicationContext parentContext){
//格式化配置文件路径
String path = String.format("classpath*:com/deppon/dop/module/%s/**/META-INF/spring/*.xml", moduleName);
applicationContext = new ClassPathXmlApplicationContext(new String[]{path},true,parentContext);
Preconditions.checkNotNull(applicationContext);
}
@SuppressWarnings("unchecked")
public <T> T getBeanByName(String name) {
return (T) applicationContext.getBean(name);
}
public <T> T getBean(Class<T> beanClass) {
Map<String, T> beanMap = applicationContext.getBeansOfType(beanClass);
Iterator<T> iterator = beanMap.values().iterator();
return iterator.hasNext() ? iterator.next() : null;
}
}
package org.ygy.demo.spring.service;
public class OneService {
public void sayOne() {
System.out.println("-- from sayOne().");
}
public void sayTwo() {
System.out.println("-- from sayTwo().");
}
}
package org.ygy.demo.spring.service;
public class AnotherService {
public void queryOne() {
System.out.println("--from queryOne().");
}
public void queryTwo() {
System.out.println("--from queryTwo().");
}
}
先记录到这,感觉有点儿不对劲儿,哪里讲的好像有问题......