我需要数据源实例,但正在获取NPE。

xml:

    <context:component-scan base-package="nl.jms" />
    <context:annotation-config />

    <!--DataSource Bean Initialization-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.postgresql.Driver"/>
        <property name="url" value="jdbc:postgresql://localhost:5432/nl"/>
        <property name="username" value="postgres"/>
        <property name="password" value="pwd"/>
    </bean>


主要方法:

public class Main {
    public static void main(String[] args) throws IOException {
        new ClassPathXmlApplicationContext("spring/applicationContext.xml");

        Schedule s = new Schedule();
        s.call();
    }
}


时间表类:

public class Schedule {
    LoginLog l = new LoginLog();
    public void call(){
        System.out.println("In SC");
        l.loginEventLogging();
    }
}


登录日志:

@Service
public class LoginLog{

    @Autowired
    private IMailEvent mailEvent;

    @Autowired
    DataSource dataSource;

    @Override
    public void loginEventLogging(){
        System.out.println("In Log");
        String checkoutSql = "select *  from transaction where data_date::date = current_date;";
        System.out.println("HERE");
        System.out.println("KKK" + dataSource);
        org.springframework.jdbc.core.JdbcTemplate template = new org.springframework.jdbc.core.JdbcTemplate(dataSource);
    }
}


错误:

Exception in thread "main" java.lang.IllegalArgumentException: Property 'dataSource' is required
    at org.springframework.jdbc.support.JdbcAccessor.afterPropertiesSet(JdbcAccessor.java:135)
    at org.springframework.jdbc.core.JdbcTemplate.<init>(JdbcTemplate.java:169)
    at ngl.jms.dbLog.LoginLog.loginEventLogging(LoginLog.java:30)
    at ngl.jms.dbLog.Schedule.call(Schedule.java:13)
    at ngl.jms.application.Main.main(Main.java:13)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:606)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)


我不明白为什么它会给我NPE错误。
救命。

最佳答案

问题是您自己实例化了LoginLog

(请参见LoginLog l = new LoginLog();中的Schedule)。

这意味着LoginLog不是由Spring管理的,因此不会发生依赖项注入。

您需要执行以下操作(将导致所有相关的类都由Spring管理):

@Component
public class Schedule {
    @Autowired
    private LoginLog l;

    public void call(){
        System.out.println("In SC");
        l.loginEventLogging();
    }
}

public class Main {
    public static void main(String[] args) throws IOException {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/applicationContext.xml");

        Schedule s = context.getBean(Schedule.class)
        s.call();
    }
}

10-08 02:34