为什么autowiring bean为null?

时间:2013-09-23 16:06:53

标签: spring spring-mvc dependency-injection autowired

我为我的应用程序编写测试:

public class CandidateServiceTest {

    @Autowired
    CandidateService candidateService;

    @BeforeClass
    public static void initialize() throws Exception{
        ApplicationContext context = new ClassPathXmlApplicationContext(
                "test/BeanConfig.xml");//I think here I load context

        UtilMethods.createTestDb();

    }

    @Test
    public void add(){
        Candidate candidate = new Candidate();
        candidate.setName("testUser");
        candidateService.add(candidate);//NullPointerException  here
        List<Candidate> candidates = candidateService.findByName(candidate.getName());
        Assert.assertNotNull(candidates);
    }
}

在行

candidateService.add(candidate);//Null entity here   here

candidateService为空。

测试/ BeanConfig.xml:

 <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:context="http://www.springframework.org/schema/context"
        xmlns:jee="http://www.springframework.org/schema/jee" xmlns:lang="http://www.springframework.org/schema/lang"
        xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx"
        xmlns:util="http://www.springframework.org/schema/util"
        xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
            http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
            http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
            http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd
            http://www.springframework.org/schema/lang http://www.springframework.org/schema/lang/spring-lang.xsd
            http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
            http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

        <!-- Включаем опцию использования конфигурационных аннотаций (@Annotation-based configuration)-->
        <context:annotation-config />


        <context:component-scan base-package="com.epam.hhsystem.jpa" />
        <context:component-scan base-package="package com.epam.hhsystem.services" />

        <!-- Файл с настройками ресурсов для работы с данными (Data Access Resources) -->
        <import resource="data.xml" />

    </beans>

data.xml - 有关hibernate的信息,

CandidateService类:

package com.epam.hhsystem.services;
     ...
    @Transactional
    @Service("candidateService")
    public class CandidateService {

        @Autowired
        private CandidateDao candidateDao;//package com.epam.hhsystem.jpa

        @Autowired
        private VacancyDao vacancyDao;//package com.epam.hhsystem.jpa

        @Autowired
        private SkillDao skillDao;//package com.epam.hhsystem.jpa

        @Autowired
        private EventDao eventDao;//package com.epam.hhsystem.jpa

        @Autowired 
        UtilService utilService;//package com.epam.hhsystem.services


        public void add(Candidate candidate) {
            Authentication auth = SecurityContextHolder.getContext().getAuthentication();
            String login = auth.getName();
            User user =  utilService.getOrSaveUser(login);
            candidate.setAuthor(user);
            candidateDao.add(candidate);
        }

        ....
    }

你能帮助我吗?

更新

我重写了代码:

@ContextConfiguration(locations = {"classpath:/test/BeanConfig.xml"})
public class CandidateServiceTest extends AbstractTransactionalJUnit4SpringContextTests{

    @Autowired
    CandidateService candidateService;

    @BeforeClass
    public static void initialize() throws Exception{

        UtilMethods.createTestDb();

    }

    @Test
    public void add(){
        Candidate candidate = new Candidate();
        candidate.setName("testUser");
        candidateService.add(candidate);
        List<Candidate> candidates = candidateService.findByName(candidate.getName());
        Assert.assertNotNull(candidates);
    }
}

我有这样的痕迹:

java.lang.NullPointerException
at com.epam.hhsystem.services.CandidateService.add(CandidateService.java:56)
at com.epam.hhsystem.services.CandidateService$$FastClassByCGLIB$$3796612d.invoke(<generated>)
at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:698)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:96)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:260)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:94)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:631)
at com.epam.hhsystem.services.CandidateService$$EnhancerByCGLIB$$afe33393.add(<generated>)
at com.epam.hhhsystem.services.CandidateServiceTest.add(CandidateServiceTest.java:40)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

4 个答案:

答案 0 :(得分:3)

您的测试用例写错了。使用框架不能解决它。使用Springs Test Support类加载和自动装配测试用例,而不是试图绕过它。

@ContextConfiguration(locations = {"classpath:/test/BeanConfig.xml"})
public class CandidateServiceTest extends AbstractTransactionalJUnit4SpringContextTests {

    @Autowired
    CandidateService candidateService;

    @Test
    public void add(){
        Candidate candidate = new Candidate();
        candidate.setName("testUser");
        candidateService.add(candidate);//NullPointerException  here
        List<Candidate> candidates = candidateService.findByName(candidate.getName());
        Assert.assertNotNull(candidates);
    }
}

我强烈建议您阅读Spring Reference Guide,特别是the section covering testing

除了没有正确使用框架之外,您没有正确设置初始状态。您正在编写单元/集成测试,并且您的CandidateService实现期望Spring Security Authentication对象可用。在测试运行之前,您没有设置一个,因此会产生NullPointerException

添加@Before方法,该方法将在测试方法之前设置它,并在此之后清除@After方法。 (或者在你的测试方法中做,但要记得正确清理!)。

@Before
public void setup() {
    TestingAuthenticationToken testToken = new TestingAuthenticationToken("testUser", "");
    SecurityContextHolder.getContext().setAuthentication(testToken);
}

@After
public void cleanUp {
    SecurityContextHolder.clearContext();
}

答案 1 :(得分:2)

我没有看到你放在这里的测试类的注释。通常,要在Spring上下文中运行测试类,需要使用以下注释:

@RunWith(SpringJUnit4ClassRunner.class) 
// This will run necessary job to load the context and inject bean into your test
@ContextConfiguration("classpath:/test-bundle-context.xml") 
// This specify the configuration used, you can use the java-config style as well (but only for Spring 3.1)
@TransactionConfiguration(transactionManager = "txManager", defaultRollback = true) 
// If you want to test the transaction, otherwise, this is not necessary
@Transactional(propagation = Propagation.SUPPORTS) 
// depend on your test natural, you can set difference propagation.

组件扫描对测试中没有任何帮助。

Maven依赖:

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>3.1.0.RELEASE</version>
    <scope>test</scope>
</dependency>

答案 2 :(得分:1)

我猜你的BeanConfig.xml是错误的,因为它包含“package”:

 <context:component-scan base-package="package com.epam.hhsystem.services" />

将其更改为:

// package removed     
<context:component-scan base-package="com.epam.hhsystem.services" />

有帮助吗?

答案 3 :(得分:0)

我遇到了类似的问题,原因并不是上面的答案。结果我的IDE插入了import org.junit.Test而不是import org.testng.annotations.Test。琐碎但很难追查。