spring - 为什么 Autowiring bean 为空?

标签 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 - 关于休眠的信息,

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)

最佳答案

你的测试用例写错了。使用框架不要绕过它。使用 Springs 测试支持类来加载和 Autowiring 您的测试用例,而不是尝试绕过它。

@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();
}

关于spring - 为什么 Autowiring bean 为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18963913/

相关文章:

spring - 如何在同一应用程序中使用 spring-sample 示例配置 spring 安全基本身份验证和 SAML 身份验证

c# - ASP.NET Core 3.1 将 appsettings.json 中的对象数组注入(inject)到注入(inject)的服务中

java - Spring Boot 不接受文件扩展名

java - Spring MVC - 没有找到请求 URI 的映射

java - 未定义 [service.NewsServiceImpl] 类型的合格 bean

c# - 依赖注入(inject)在 C++ 中有用吗

flutter - Dart 依赖注入(inject) - 为什么我不能将实例引用传递给类成员?

javascript - Node.js HTTP GET “ECONNRESET” 读取错误

java - Spring 的新手 - 应用程序上下文何时/何地实例化所有 bean

JVM 崩溃后的 Spring Batch