java Spring Framework 自动装配空指针异常

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25298427/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 07:48:21  来源:igfitidea点击:

Spring Framework Autowired Null Pointer Exception

javaspringjdbcdependency-injection

提问by Ben Harris

I'm learning Spring and I'm having some problems trying to set up a relatively basic Spring project. I'm creating an application to simply read from a database, but I'm having problems with Autowiring, or lack thereof. My GetCustomerEventclass is throwing a null pointer exception in the GetCustomers()method, as the CustomerServicevariable hasn't been initialised. Can someone point me in the right direction here?

我正在学习 Spring,但在尝试建立一个相对基本的 Spring 项目时遇到了一些问题。我正在创建一个应用程序来简单地从数据库中读取数据,但是我遇到了自动装配问题或缺乏自动装配问题。我的GetCustomerEvent类在GetCustomers()方法中抛出空指针异常,因为CustomerService变量尚未初始化。有人可以在这里指出我正确的方向吗?

Application.class

应用程序类

package org.ben.test.main;
@Configuration
@ComponentScan(basePackages={"org.ben.test.persistence", "org.ben.test.main"})
public class Application {

    @Bean
    public CustomerService customerService() {
        return new CustomerService();
    }

    @Bean 
    public DataSource getDataSource() {
        DriverManagerDataSource dmds = new DriverManagerDataSource();
        dmds.setDriverClassName("org.postgresql.Driver");
        dmds.setUrl("jdbc:postgresql://localhost:5432/Customers");
        dmds.setUsername("postgres");
        dmds.setPassword("postgres");
        return dmds;

    }

    @Bean
    public JdbcTemplate jdbcTemplate() {
        DataSource ds = getDataSource();
        JdbcTemplate jdbc = new JdbcTemplate(ds);
        return jdbc;
    }

    public static void main(String[] args) {
        GetCustomerEvent ev = new GetCustomerEvent();
        ev.GetCustomers();
    }
}

CustomerService.class

客户服务类

package org.ben.test.persistence;

@Component
public class CustomerService {

    @Autowired JdbcTemplate jdbcTemplate;

    public CustomerService() {

    }

    public void getCustomers() {
        jdbcTemplate.query("SELECT * FROM Customers", new RowMapper() {
            @Override
            public Object mapRow(ResultSet arg0, int arg1) throws SQLException {
                System.out.println(arg0.getString("firstName"));
                return null;
            }
        });
    }

}

GetCustomerEvent.class

获取客户事件.class

package org.ben.test.persistence;


@Component
public class GetCustomerEvent {

    @Autowired 
    CustomerService customerService;

    public GetCustomerEvent() {

    }

    public void GetCustomers() {
        customerService.getCustomers();
    }
}

回答by user3543576

Problem is with below line

问题出在下面的行

GetCustomerEvent ev = new GetCustomerEvent();

You manually created instance using "new". Spring does not have idea about this object. See Why is my Spring @Autowired field null?for details.

您使用“new”手动创建了实例。Spring 不知道这个对象。请参阅为什么我的 Spring @Autowired 字段为空?详情。

回答by Evandro Pomatti

You are not initializing the Spring Container.

您没有初始化 Spring 容器。

You need to create your contextin order for it to work.

您需要创建上下文才能使其正常工作。

回答by Naresh Vavilala

You need to create the application context no matter if you are using xml or annotation based configuration. If your application is a web application, see this post Loading context in Spring using web.xmlto load the application context

无论您使用 xml 还是基于注解的配置,都需要创建应用程序上下文。如果您的应用程序是 Web 应用程序,请参阅这篇文章Loading context in Spring using web.xmlto load the application context

Once you have the application you can get the bean using context.getBean()method

拥有应用程序后,您可以使用context.getBean()方法获取 bean

Also, spring container does not manage the objects you create using new operator. In your example you need to autowire the GetCustomerEvent bean

此外,spring 容器不管理您使用 new 运算符创建的对象。在您的示例中,您需要自动装配 GetCustomerEvent bean

@Autowired GetCustomerEvent getCustomerEvent;
//and call
getCustomerEvent.getCustomers();