不需要再写JdbcConfig类;直接注入直接注入DataSource和使用@Transactional注解
目录结构:
1 添加依赖
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>springboot_learn</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<artifactId>spring-boot-starter-parent</artifactId>
<groupId>org.springframework.boot</groupId>
<version>2.1.6.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<!--不传递依赖-->
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<!--jdbc-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
</dependencies>
</project>
2 创建数据库连接参数的配置文件
spring中配置datasource;注意使用默认的hikari
application.yml
# 激活配置文件;需要指定其他配置文件的名称
spring:
profiles:
active: abc,def
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: root
# tomcat 端口设置
server:
port: 80
3 改造处理器类注入数据源并使用
直接注入DataSource和使用@Transactional注解
HelloController
package li.chen.com.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.sql.DataSource;
@RestController
public class HelloController {
@Autowired
private DataSource dataSource;
@Transactional
@GetMapping("hello")
public String hello() {
System.out.println("itcastUrl=" + itcastUrl);
System.out.println("itheimatUrl=" + baidutUrl);
System.out.println("DataSource=" + dataSource);
return "hello,spring boot";
}
}
4 运行启动类
Application
package li.chen.com;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
* @ClassName: Application
* @SpringBootApplication: spring boot 工程都有的启动导航类,
* 这是工程的入口类,并在引导类上添加 @SpringBootApplication
**/
@SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class,args);
}
}
查看结果
刷新请求路径
http://localhost/hello
使用debug,可以看到HelloController 获取的数据