spring boot autoconfiguration with jdbc template autowiring dataSource issue

前端 未结 1 443
情书的邮戳
情书的邮戳 2020-12-14 10:36

I\'m new to Spring and to J2EE in general. I\'m having trouble using JDBC template with Spring Boot autoconfiguration.

What I did was I took the example of RESTful w

相关标签:
1条回答
  • 2020-12-14 11:12

    The simplest way to configure a DataSource in Spring Boot is to create an application.properties file under src/main/resources with the following content (may need to update it with correct url, username and password):

    spring.datasource.url=jdbc:mysql://localhost/:3306/databasename
    spring.datasource.username=root
    spring.datasource.password=password
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    

    Spring Boot will automatically create the DataSource class for you and inject it to other beans. As a result of that, you won't need the xml config file anymore and may get rid of this line in the Application class:

    @ImportResource("classpath:spring/application-config.xml")
    

    Also, in the UserDAOImpl Spring can autowire the JdbcTemplate object using the DataSource bean (http://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-sql.html#boot-features-using-jdbc-template) so you don't need to create one each time the insert() method is called.

    As for the init() method in UserDAOImpl, you could create a schema.sql file under src/main/resources and move the CREATE TABLE statement there (for more details see http://docs.spring.io/spring-boot/docs/1.2.0.RELEASE/reference/htmlsingle/#howto-intialize-a-database-using-spring-jdbc)

    See this example for more information: http://xantorohara.blogspot.ca/2013/11/spring-boot-jdbc-sample.html

    0 讨论(0)
提交回复
热议问题