我有一个 bean mongoService 看起来像
<?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: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/util http://www.springframework.org/schema/util/spring-util-2.0.xsd">
<context:property-placeholder location="file:///storage//local.properties"/>
<bean id="mongoService" class="com.business.persist.MongoService">
<constructor-arg value="${host}"/>
<constructor-arg value="${port}"/>
<constructor-arg value="${database}"/>
</bean>
</beans>
我需要将这个 bean 包含在一个单独的项目中,所以我为这个项目创建了一个 jar 并添加为 maven 依赖项,看起来像
<dependency> <groupId>com.project</groupId> <artifactId>business</artifactId> <version>master-SNAPSHOT</version> </dependency>
现在在我需要注入(inject)该字段的文件中,我执行以下操作
public class DocumentSaver implements IDocumentSaver { @Resource private MongoService mongoService; public boolean addDocument(Document doc) { // do other things // add document to mongo mongoService.putDocument(document); return true; } }
然后我按如下方式运行测试
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("/com/wireup.xml")
public class DocumentSaverTest extends DocumentCase {
@Test
public void loadAndSave() {
DocumentSaver saver = new DocumentSaver();
Document doc = new Document();
// fill the doc
saver.addDocument(doc);
}
}
当我在类似 saver.addDocument(doc);
NullPointerException
请告诉我哪里做错了
谢谢
最佳答案
你不应该像下面这样使用 NEW 运算符创建“DocumentSaver”,从 Spring Application Context 中获取它。
DocumentSaver saver = new DocumentSaver();
如果使用 NEW 操作,Spring 不会注入(inject)依赖对象。
关于java - Spring:包含bean时发生NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11315901/