1.新建一个springboot的项目
1:在线创建一个springboot的项目
网址:https://start.spring.io
2:在本地修改pom.xml的文件即可,并建立相应的文件目录的结构。
springboot的文件的结构:
src
|main
|java
|resources
|static 存放静态的资源
|templates 存放模板的文件相当于是jsp
|application.properties 存放一些配置的文件
|test
注意入口类的文件级别不能比其他的serivce controller domain等其他的文件的级别低
入口类必须存在否则会存在一个 FileNotFoundException的异常
springboot 自定义连接池
(1):现在pom.xml的文件里面导入一个连接池的依赖
(2):在统一的入口处新建一个数据库连接池的对象,并使用@Bean注解,将一个新建的一个数据库连接池的对象交给spring的容器。
代码如下:
@Bean //使用@Bean的注解 将新创建的数据库连接池的对象交给spring的容器
public DataSource getDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://localhost:3306/demo?serverTimezone=GMT%2B8&useSSL=false&useServerPrepStmts=true&cachePrepStmts=true&rewriteBatchedStatements=true&useCursorFetch=true&defaultFetchSize=100&allowPublicKeyRetrieval=true");
dataSource.setUsername("root");
dataSource.setPassword("123");
dataSource.setMaxActive(10);
dataSource.setMinIdle(1);
return dataSource;
}
改进的地方:在统一入口进行创建一个数据库的连接池的对象的时候,参数是固定的,不灵活,改进的方案是自己编写一个DataSourceProperties的类,利用*.properties的文件参数的注入,然后在进行数据库的配置的时候将DateSourceProperties的对象的被注入的参数赋值给数据源。
代码如下:
@Component//用来让spring的容器扫描到并进行管理
@ConfigurationProperties(prefix = "hhhhh.druid")//这里是用来将配置文件的*.properties的文件进行注入
public class DataSourceProperties {
private String driverClassName;
private String URL;
private String username;
private String password;
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
private int maxActive;
private int minIdle;
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public String getURL() {
return URL;
}
public void setURL(String URL) {
this.URL = URL;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public int getMaxActive() {
return maxActive;
}
public void setMaxActive(int maxActive) {
this.maxActive = maxActive;
}
public int getMinIdle() {
return minIdle;
}
public void setMinIdle(int minIdle) {
this.minIdle = minIdle;
}
}
@Component注解是将这个类交给spring的容器去管理,@ConfigurationProperties 注解的意思是将.properties的文件的相关的参数进行了注入*
然后将上面的对象的各个属性的值赋值给数据库连接池的各个参数
@Autowired
DataSourceProperties dataSource2;
@Bean
public DataSource getDataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(dataSource2.getDriverClassName());
dataSource.setUrl(dataSource2.getUrl());
dataSource.setUsername(dataSource2.getUsername());
dataSource.setPassword(dataSource2.getPassword());
dataSource.setMaxActive(dataSource2.getMaxActive());
dataSource.setMinIdle(dataSource2.getMinIdle());
return dataSource;
}
springboot的单元测试类的使用
利用@RunWith() 和 @SpringTest()的注解的使用