java - Spring:包含bean时发生NullPointerException

标签 java spring

我有一个 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/

相关文章:

Java 同步块(synchronized block)未按预期工作

java - 使用 AlarmManager 设置一些通知并取消其中之一

java - 将对象从测试文件添加到类中的数组中?

spring - 为什么@ConfigurationProperties 注解不是spring-core 项目的一部分?

java - Spring Boot 不记录 CQL 查询

javaReflection 返回实现特定接口(interface)的类列表

java - 如何在另一个 servlet 中访问同一个 ServletContext 对象?

java - 为什么 spring 不使用我的构造函数来初始化这个 bean(Map 参数)

java - 如何在 testng 工厂类中使用 spring Autowiring

java - 从网络存档执行命令