无法与MongoDB连接

时间:2016-04-21 14:33:00

标签: java spring mongodb spring-boot

我的Java项目存在一些问题,使用Spring和MongoDB,代码如下。

我尝试使用jira.path和spring.data.mongodb.port通过 jiraConfig.properties 连接数据库,但它不起作用,我无法找到解决方案。我忘记了什么吗?

public class JiraProjectBriefControllerImpl implements JiraProjectBriefController {



  @Autowired
    JiraProjectBriefRepository jiraProjectBriefRepository;

    @Override
    public void update() {
        JiraController jiraController = new JiraControllerImpl();

        List<ProjectBrief> projectBriefs = jiraController.getAllProjectsBrief();

         jiraProjectBriefRepository.save(projectBriefs);
    }

    @Override
    public List<ProjectBrief> getProjectsBrief() {
        return jiraProjectBriefRepository.findAll();
    }

    @Override
    public ProjectBrief findById(int id) {
        return jiraProjectBriefRepository.findById(id);
    }}

//第二课

@Configuration
@EnableAutoConfiguration
public interface JiraIntegrationService {

    static void main(String[] args) {

        SpringApplication.run(JiraIntegrationService.class, args);

        JiraProjectBriefController jiraProjectBriefController = new JiraProjectBriefControllerImpl();

        jiraProjectBriefController.update();

        System.out.print(jiraProjectBriefController.getProjectsBrief());
    }

}

//错误

java.lang.reflect.InvocationTargetException
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.boot.maven.AbstractRunMojo$LaunchRunner.run(AbstractRunMojo.java:478)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.NullPointerException
    at pl.ie.service.JiraProjectBriefControllerImpl.update(JiraProjectBriefControllerImpl.java:23)
    at pl.ie.JiraIntegrationService.main(JiraIntegrationService.java:26)
    ... 6 more

2 个答案:

答案 0 :(得分:1)

当你在一个对象上调用new时,就像你在main中一样,这意味着Spring已经不在了。对象的创建和满足其依赖性取决于您。

您不应该调用new来创建该对象。最好实例化Spring Bean工厂,并要求它为您提供所需的实例,并连接所有依赖项。

这是新Spring用户常见的误解。他们调用new并且无法理解为什么他们的Spring依赖关系没有连线。

答案 1 :(得分:0)

jiraProjectBriefRepository尚未初始化。