[英]@Autowired not able to inject bean in class under test
I am doing unit test on a class which contains a variable that is @Autowired
by spring. 我正在对一个类进行单元测试,该类包含一个由弹簧
@Autowired
的变量。 However, when I run the test, I get a NullPointerException
indicating object userDetailsLoader
is null. 但是,当我运行测试时,我得到一个
NullPointerException
指示对象userDetailsLoader
为null。
Following is what I have: 以下是我所拥有的:
public class UserService {
@Autowired
UserDetailsLoader userDetailsLoader;
public void doSomething (){...}
}
JUnit test class: JUnit测试类:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration
public class UserServiceTest {
UserService service = new UserService();
@Test
public void testDoSomething() {...}
}
UserServiceTest-context.xml: UserServiceTest-context.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">
<bean id="userDetailsLoader" class="my.package.UserDetailsLoader" />
</beans>
The configuration file is properly named and there is no FileNotFoundException
. 配置文件已正确命名,并且没有
FileNotFoundException
。 Can anybody see the problem here? 谁能在这里看到问题?
Thank you in advance. 先感谢您。
Well, I guess I am just being dumb on Monday, still recovering from ending of weekends. 嗯,我想我周一只是愚蠢,仍然从周末结束后恢复。
The problem is simple and obvious. 问题很简单明了。 I am creating a bean that is not managed by Spring since I wrote
UserService service = new UserService();
我正在创建一个不受Spring管理的bean,因为我编写了
UserService service = new UserService();
in the test calss. 在测试中。 In order for a bean to be injected by spring, spring has to be aware of it and has relevant information of it.
为了通过弹簧注入豆子,春天必须意识到它并且具有相关的信息。 In my case, I have the config ready (relevant info), but the bean is not injected by Spring (not
@Autowired
). 在我的情况下,我有配置就绪(相关信息),但bean不是由Spring注入的(不是
@Autowired
)。
In conclusion, changing UserService service = new UserService();
总之,更改
UserService service = new UserService();
to 至
@Autowired UserService service;
solved the problem. 解决了这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.