Spring動態載入配置檔案
阿新 • • 發佈:2019-02-13
最近在專案中學習到,動態的載入配置檔案,就從網上查閱資料,整理了一篇部落格《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()."); } }
先記錄到這,感覺有點兒不對勁兒,哪裡講的好像有問題......