junit用在spring mvc框架中報錯:找不到service層中的bean
阿新 • • 發佈:2019-02-14
專案結構:
用junit寫的測試類DubboTest.java;
spring用的配置檔案 applicationContext.xml spring mvc用的配置檔案 servlet-context.xml 在DubboTest.java中用註解載入了applicationContext.xml檔案,程式碼如下: package com.lpf.study.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.lpf.study.service.StudyService;
@RunWith(SpringJUnit4ClassRunner. class)
@ContextConfiguration(locations
= {"classpath:applicationContext.xml" })
public class DubboTest extends AbstractJUnit4SpringContextTests
{
@Autowired StudyService studyServiceImpl;
@Test
public void testUseDubbo(){
System. out.println( studyServiceImpl.sayHello());
}
}
剛開始一直報 Autowired不到 StudyService,經分析,是由於DubboTest.java只加載了spring用的applicationContext.xml,
@ContextConfiguration (locations
= {"classpath:applicationContext.xml" }),我用的又是spring的註解功能,但是在applicationContext.xml
中又沒有加入component-scan元素。所以解決辦法就是在applicationContext.xml中加入<context:component-scan>元素。
要注意的是,加component-scan元素,要給applicationContext.xml加xmlns:context ="http://www.springframework.org/schema/context"
名稱空間以及配套的xsd
http://www.springframework.org/schema/context
我做的時候遇到了點問題,我的applicationContext.xml中的schemaLocation本身用的是
我加入component-scan元素和名稱空間、xsd後applicationContext.xml報錯,且執行DubboTest.java報錯,後來換成了
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd,問題解決。
spring用的配置檔案 applicationContext.xml spring mvc用的配置檔案 servlet-context.xml 在DubboTest.java中用註解載入了applicationContext.xml檔案,程式碼如下: package com.lpf.study.test; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired;