2017-01-20 45 views
0

我正在创建一个Spring启动应用程序,我正在初始化spring文件中的数据源。但是,得到如下错误:数据源无法通过Spring启动应用程序进行初始化?

java.lang.NullPointerException: null 
    at com.howtodoinjava.demo.controller.JdbcCustomerDAO.insert(JdbcCustomerDAO.java:28) ~[classes/:na] 
    at com.howtodoinjava.demo.controller.EmployeeController.getCustomer(EmployeeController.java:36) ~[classes/:na] 
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_91] 
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_91] 
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_91] 
    at java.lang.reflect.Method.invoke(Method.java:498) ~[na:1.8.0_91] 
    at org 

获得NullPointerException异常下面一行:

conn = dataSource.getConnection(); 

我的源代码是有在GitHub https://github.com/thesnehajain/spring_boot/tree/master/springbootdemo

+0

这是因为'dataSource'是没有得到注射;尝试使用'@ Autowired'注释构造函数注入,稍后调整它以使用setter注入 –

+0

Stil注释后给出相同的错误。 – Vicky

回答

1

删除你的XML文件(所有的人!)。

创建一个新的文件application.propertiessrc/main/resources,并把这个里面:

spring.datasource.driverClassName = com.mysql.jdbc.Driver 
spring.datasource.url = jdbc:mysql://rdssample.xxxxxx.us-west-2.rds.amazonaws.com:3306/customer 
spring.datasource.username = rdssample 
spring.datasource.password = rdssample 
#spring.jpa.hibernate.ddl-auto = create-drop 
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect 

...,应该使的伎俩! Spring Boot是关于约定和发现的一切,所以你不必定义,声明(继续)所有的bean和依赖关系。你可以获得很多只是声明一些“属性”。

UPDATE

Spring配置,在这两个“口味”(XML和Java类),是在春季启动允许的,但同样,春季启动应用程序需要很少没有的配置,绝对没有代码生成并且不需要XML配置。它可能看起来像一个传统的Spring MVC应用程序,但它实际上非常不同。看看Spring Boot Reference Guide,你会发现很多有用的提示和例子。

而且,在你的情况下,如果要配置通过Java配置数据源,你可以做一些与此类似:

@Configuration 
public class DataConfig { 
    @Bean 
    public DataSource dataSource() { 
    return DataSourceBuilder.create() 
     .driverClassName("com.mysql.jdbc.Driver") 
     .username("rdssample") 
     .password("rdssample") 
     .url("jdbc:mysql://rdssample.xxxxxx.us-west-2.rds.amazonaws.com:3306/customer") 
     .build(); 
    } 
} 
+0

在springboot应用程序中不允许使用spring配置吗?同时我正在尝试你的解决方案。 – Vicky

+0

谢谢。你的解决方案已经奏效但是,你能回答我的上述问题吗? – Vicky

+0

我在答案中加入了“更新”条款,以备将来参考,以防某人需要做相同的更改 –

相关问题