導航:首頁 > 文件管理 > 配置文件參數注入

配置文件參數注入

發布時間:2024-03-24 21:11:12

㈠ Spring配置文件中如何注入另一個XML中的配

主要有兩種方式:
1、在一個配置文件中使用import標簽導入其他配置文件,即

applicationContext.xml中部分代碼如下:<import resource="applicationContext-.xml" /><import resource="applicationContext-service.xml" /><import resource="applicationContext-action.xml" />

2、在web.xml中配置Spring配置文件處導入多個配置文件,即可
a、導入多個配置文件

web.xml部分代碼如下:<context-param> <param-name>contextConfigLocation</param-name> <param-value> applicationContext-core.xml, applicationContext-.xml, applicationContext-service.xml, applicationContext-action.xml </param-value></context-param>

b、使用*通配符導入多個配置文件

web.xml部分代碼如下:<context-param> <param-name>contextConfigLocation</param-name> <param-value> applicationContext-*.xml </param-value></context-param>

㈡ spring 配置文件的bean自動注入失敗的解決方法是什麼

一個Spring注入問題,首先看一個普通Spring Bean,

publicclassFoo{
@Autowired
Barbar;

publicvoiddoSomething(){
bar.doSomething();
}
}

Spring配置一:

<beanid="bar"class="com.test.Bar"></bean>
<beanid="foo"class="com.test.Foo"></bean>

單元測試:

@Test
publicvoidtest_doSomthing(){
ApplicationContextctx=("applicationContext-test.xml");
Foofoo=ctx.getBean(Foo.class);
foo.doSomething();
}

執行上述測試方法,報錯

java.lang.NullPointerException
atcom.test.Foo.doSomething(Foo.java:15)
atcom.test.FooTest.test_doSomthing(FooTest.java:13)

即foo bean中的bar並未注入。

Spring配置二:

<context:component-scanbase-package="com.test"></context:component-scan>

當改成配置二後執行上述單元測試方法便能成功通過。經分析日誌及查看源代碼,發現使用配置二時供裝載了6個bean,如下所示:

DEBUGorg.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)[applicationContext-test.xml]
DEBUGorg.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:530)Beanfactoryfororg.springframework.context.support.@3c4e80d3:org.springframework.beans.factory.support.DefaultListableBeanFactory@14cc51c8:definingbeans[bar,foo,org.springframework.context.annotation.,org.springframework.context.annotation.,org.springframework.context.annotation.,org.springframework.context.annotation.];rootoffactoryhierarchy

而使用配置一時只有兩個bean,如下所示:

DEBUGorg.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)[applicationContext-test.xml]
DEBUGorg.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:530)Beanfactoryfororg.springframework.context.support.@45ebbb93:org.springframework.beans.factory.support.DefaultListableBeanFactory@18481697:definingbeans[bar,foo];rootoffactoryhierarchy

配置二執行單元測試通過的原因似乎就在於多出的這幾個bean。是不是只要有context:component-scan元素在自動就會有這幾個bean的產生?驗證此假設

在配置一中添加一個無實際意義的context:component-scan元素,如下所示:

<context:component-scanbase-package="com.nonexist"></context:component-scan>

這時執行單元測試能通過,同配置二一樣也會裝載6個bean。那麼這6個bean中到底哪個對注入bar到Foo中起了作用呢?

經過斷點調試發現是 bean起了作用,見輸出日誌:

2015-04-2520:23:09DEBUGorg.springframework.beans.factory.annotation.InjectionMetadata.<init>(InjectionMetadata.java:60)Foundinjectedelementonclass[com.test.Foo]:AutowiredFieldElementforcom.test.Barcom.test.Foo.bar
2015-04-2520:23:09DEBUGorg.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:85)'foo':AutowiredFieldElementforcom.test.Barcom.test.Foo.bar
2015-04-2520:23:09DEBUGorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:245)'bar'
2015-04-2520:23:09DEBUGorg.springframework.beans.factory.annotation..registerDependentBeans(.java:424)Autowiringbytypefrombeanname'foo'tobeannamed'bar'
2015-04-2520:23:09DEBUGorg.springframework.beans.factory.support..createBean(.java:458)'foo'

那麼直接在配置一種顯式添加bean呢?如下所示:

<beanid="bar"class="com.tcl.account.service.test.Bar"></bean>
<beanid="foo"class="com.tcl.account.service.test.Foo"></bean>
<beanid=""class="org.springframework.beans.factory.annotation."></bean>

測試會不會通過?會通過。見日誌:

DEBUGorg.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)[applicationContext-test.xml]
DEBUGorg.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:530)Beanfactoryfororg.springframework.context.support.@7767d3c1:org.springframework.beans.factory.support.DefaultListableBeanFactory@1924ed52:definingbeans[bar,foo,];rootoffactoryhierarchy
DEBUGorg.springframework.beans.factory.annotation.InjectionMetadata.<init>(InjectionMetadata.java:60)Foundinjectedelementonclass[com.test.Foo]:AutowiredFieldElementforcom.test.Barcom.test.Foo.bar
DEBUGorg.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:85)'foo':AutowiredFieldElementforcom.test.Barcom.test.Foo.bar
DEBUGorg.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:245)'bar'
DEBUGorg.springframework.beans.factory.annotation..registerDependentBeans(.java:424)Autowiringbytypefrombeanname'foo'tobeannamed'bar'
DEBUGorg.springframework.beans.factory.support..createBean(.java:458)'foo'

那麼為什麼在配置文件中添加了context:componet-scan元素後就會自動添加那另外4個bean呢?經過斷點調試發現Spring隱式裝載的4個bean是在如下方法中載入的:

Set<BeanDefinitionHolder>org.springframework.context.annotation.AnnotationConfigUtils.(,Objectsource)

其調用鏈如下所示:

補充一:

若仍用配置一,但單元測試改成如下形式也可以測試通過。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:/applicationContext-test.xml"})
publicclassFooTest2{
@Autowired
privateFoofoo;
@Test
publicvoidtest_doSomthing(){
foo.doSomething();
}
}

當然一點都不意外,這種方式也會隱式載入那4個bean,見日誌:

DEBUGorg.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:216)[classpath:/applicationContext-test.xml]
INFOorg.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:500)Refreshingorg.springframework.context.support.GenericApplicationContext@51f3336e:startupdate[SunApr2617:27:35CST2015];rootofcontexthierarchy
DEBUGorg.springframework.context.support.AbstractApplicationContext.obtainFreshBeanFactory(AbstractApplicationContext.java:530)Beanfactoryfororg.springframework.context.support.GenericApplicationContext@51f3336e:org.springframework.beans.factory.support.DefaultListableBeanFactory@4f9d1352:definingbeans[bar,foo,org.springframework.context.annotation.,org.springframework.context.annotation.,org.springframework.context.annotation.,org.springframework.context.annotation.];rootoffactoryhierarchy

補充二,若使用的是@Value,效果同@Autowired,即也需要隱式載入 bean。

publicclassFoo{
@Value("${bar}")
Stringbar;

publicvoiddoSomething(){
System.out.println(bar);
}
}

補充三:

若使用配置一,@PostConstruct標注的方法也不會被執行,但此時需要隱式載入的Spring bean是:org.springframework.context.annotation.

補充四:

在配置一中添加如下配置

<context:annotation-config/>

也會隱式載入那4個bean

㈢ 怎麼創建junit4 注入spring 配置文件

1 建立一個test的目錄,在此目錄下放置所有的JunitTestCase類和TestCase的配置文件
2 將項目中的Spring配置文件(默認名稱為applicationContext.xml)復制到test目錄下,並重新命名為JunitTestConf.xml。
3 根據Junit測試的需要修改JunitTestConf.xml文件中的內容,如資料庫連接等。
4 新建一個名為SpringConfForTest.java的類,在此類中配置Spring啟動所需的配置文件,並啟動Spring。此類的內容如下:
package test;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.;
import com.soma.global.WebContextHolder;
public class SpringConfForTest {

@BeforeClass
public static void setUpBeforeClass() throws Exception {
//Spring啟動所需要的配置參數文件,其中test/JunitTestConf.xml文件中保存了資料庫連接等參數,可根據具體情況做修改
String[] paths = new String[] {"test/JunitTestConf.xml", "com/soma/conf/applicationContext--hr.xml","com/soma/conf/applicationContext-.xml","com/soma/conf/applicationContext--bug.xml","com/soma/conf/applicationContext--change.xml","com/soma/conf/applicationContext--common.xml","com/soma/conf/applicationContext-service-hr.xml" };
//啟動Spring,得到Spring環境上下文
ApplicationContext ctx = new (paths);
//在此類啟動時,將Spring環境上下文保存到單根類WebContextHolder中,以提供給其它的測試類使用
WebContextHolder.getInstence().setApplicationContext(ctx);
}
@AfterClass
public static void tearDownAfterClass() throws Exception {
}
@Test
public void test(){
//必須要寫一個test空方法,否則SpringConfForTest類不會啟動
}
}
5 新建TestSuite類,類名為AllTests,類的內容如下所示:
package test;
import junit.framework.Test;
import junit.framework.TestSuite;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
import test.com.soma.domain.busilogic.hr.HrBusiLogicTest;
import test.com.soma.domain.service.hr.checkOverTimeDateTest;
@RunWith(Suite.class)
@Suite.SuiteClasses({
SpringConfForTest.class,
HrBusiLogicTest.class,
checkOverTimeDateTest.class
})
/**
* 批量執行Junit測試類,把類名寫入到上面的Suite.SuiteClasses({})中,用逗號分隔
*/
public class AllTests {
public static Test suite() {
TestSuite suite = new TestSuite("Test for test");
//$JUnit-BEGIN$
//$JUnit-END$
return suite;
}
}
注意:將SpringConfForTest.class放在第一個執行,以啟動Spring配置環境,把自己的TestCase類放到後面,用逗號分開。在測試時,只要執行這個TestSuite類就可以了。
6 寫自己的TestCase類,以CheckOverTimeDateTest.java為例子,文件內容如下:
public class CheckOverTimeDateTest {
private static HrTbovertimeManager hrTbovertimeManager;
private static ExcuteSqlDAO excuteSqlDAO;
@BeforeClass
public static void setUpBeforeClass() throws Exception {
//從Spring上下文中得到hrTbovertimeManager介面類的實例
hrTbovertimeManager=(HrTbovertimeManager)BeanUtil.getBean("hrTbovertimeManager");
excuteSqlDAO = (ExcuteSqlDAO) BeanUtil.getBean("excuteSqlDAO");
}
@Test
public void testGetProjectList()throws Exception {

List<OvertimeDetailValue> overtimeDetailValueList = new ArrayList<OvertimeDetailValue>();
int index = 9;
for(int i = 1 ;i <= index;i++){
OvertimeDetailValue overtimeDetailValue = new OvertimeDetailValue();
overtimeDetailValue.setOtApplyDate("2009-05-0"+i);
overtimeDetailValueList.add(overtimeDetailValue);
}
String resultStr = hrTbovertimeManager.checkOverTimeDate(overtimeDetailValueList);
assertEquals("false", resultStr);
}
/**
* 導入2009-03月份出勤記錄excel文件,返回null表示導入成功,需要先刪除3月份的數據
*/
@Test
public void testSaveExcelDutyInformation() throws Exception{
// 在導入3月份出勤記錄前先刪除3月份的記錄,執行delete from hr_tbtyinformation;
excuteSqlDAO.excuteSql("delete from hr_tbtyinformation where tydate>='2009-02-26' and tydate<='2009-03-25'");
// System.out.println("----------"+System.getProperty("user.dir")+"/src/test/ty200903.xls");
String fileName = System.getProperty("user.dir")
+ "/src/test/ty200903.xls";
assertNull(hrTbtyInformationManager.saveExcelDutyInformation(fileName));
}
}
說明:BeanUtil.getBean("")相當於WebContextHolder.getInstence().getApplicationContext().getBean(""),只是對此方法做了封裝。
7 在Eclipse中,啟動AllTests,選擇「Run As JunitTest」,即可先啟動Spring環境,再依次運行你自己所寫的JunitTestCase,是不是很簡單哪?趕快動手試試吧。

閱讀全文

與配置文件參數注入相關的資料

熱點內容
公牛蘋果數據線怎麼樣 瀏覽:392
內存數據在哪個部件讀取 瀏覽:34
頻率檢測程序 瀏覽:952
怎麼做網站付費鏈接 瀏覽:662
js在當前頁面刷新 瀏覽:223
高級攝影閃光燈應用視頻教程下載 瀏覽:804
怎麼把圖片加入視頻文件夾 瀏覽:734
滑鼠右鍵的壓縮文件 瀏覽:44
awr導出cad文件 瀏覽:925
參公文件去哪裡找 瀏覽:827
excel表批量日期設置成文件夾存放 瀏覽:90
如何把資料庫加入其中 瀏覽:661
編程除法怎麼取消取整 瀏覽:625
股票編程軟體哪裡有賣 瀏覽:503
access導入多個txt文件 瀏覽:917
大臉app安卓下載 瀏覽:439
怎麼休改文件名 瀏覽:989
cdr導出圖片不顯示文件名 瀏覽:761
pcdmis如何離線編程 瀏覽:201
微信推文插入文件 瀏覽:844

友情鏈接