在Spring Boot中配置DataSource数据源,可以通过以下步骤进行:
1. 在`application.properties`或`application.yml`文件中,配置数据库连接信息,例如:
`application.properties`文件配置示例:
spring.datasource.url=jdbc:mysql://localhost:3306/mydb spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` - `application.yml`文件配置示例: ```yaml spring:??datasource:
????url:?jdbc:mysql://localhost:3306/mydb
????username:?root
????password:?123456
????driver-class-name:?com.mysql.cj.jdbc.Driver
2. 在Spring Boot应用的配置类中,使用@EnableAutoConfiguration注解启用自动配置,并使用@ConfigurationProperties注解将配置信息注入到DataSource对象上,例如:
import?org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import?org.springframework.boot.context.properties.ConfigurationProperties;
import?org.springframework.context.annotation.Bean;
import?org.springframework.context.annotation.Configuration;
import?org.springframework.jdbc.datasource.DriverManagerDataSource;
import?javax.sql.DataSource;
@Configuration
@EnableAutoConfiguration
public?class?DataSourceConfig?{
????@Bean
????@ConfigurationProperties(prefix?=?“spring.datasource”)
????public?DataSource?dataSource()?{
????????return?new?DriverManagerDataSource();
????}
}
3. 在需要使用数据源的地方,使用@Autowired注解将DataSource对象注入进来即可使用,例如:
import?org.springframework.beans.factory.annotation.Autowired;
import?org.springframework.jdbc.core.JdbcTemplate;
import?org.springframework.stereotype.Component;
@Component
public?class?MyComponent?{
????private?final?JdbcTemplate?jdbcTemplate;
????@Autowired
????public?MyComponent(DataSource?dataSource)?{
????????this.jdbcTemplate?=?new?JdbcTemplate(dataSource);
????}
????//?使用jdbcTemplate进行数据库操作
????//?…
}
通过以上配置,就可以在Spring Boot中使用DataSource数据源进行数据库操作了。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: springboot前后端交互流程是什么