目录
创建普通maven工程,然后通过配置使其成为springboot工程
为什么要用springboot
- 1、复杂的配置,配置已经由springboot配置好放在启动器内部
- 2、统一的版本管理
- 3、内嵌Tomcat简易优化
快速创建工程的两种方式
-
IDEA编译器下,直接创建springboot工程
new project -> Spring Initializr -> next -> next
-
创建普通maven工程,然后通过配置使其成为springboot工程
a.配置pom
spring-boot-starter-parent统一管理版本,引入启动器时不用带版本
spring-boot-starter-web是启动器【引入启动器,若不配置@Bean,则会使用springboot默认的实现,例如默认数据源HiKariCP】
<?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>com.leyou.parent</groupId>
<artifactId>leyou</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>leyou</name>
<description>Demo project for Spring Boot</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.9.RELEASE</version>
<relativePath/>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
b.配置启动类
@SpringBootApplication(scanBasePackages = "com")\\默认从当前包开始扫描下级包
public class SpringbootDemoApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootDemoApplication.class, args);
}
}
c.配置连接池datasource
添加依赖:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.6</version>
</dependency>
属性文件:jdbc.properties
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/springbootdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
配置数据源datasource:
传统xml方式:1.扫描配置文件;2.配置数据源bean;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd">
<!-- 自动扫描类包 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package="com.datadriver">
<context:exclude-filter type="regex" expression="com.datadriver.web.invest.*"/>
<context:exclude-filter type="regex" expression="com.datadriver.web.databus.*"/>
<context:exclude-filter type="regex" expression="com.datadriver.alg.*"/>
</context:component-scan>
<context:component-scan base-package="com.haikai" />
<!-- 引入配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:jdbc.properties</value>
<value>classpath*:application.properties</value>
<value>classpath*:cron.properties</value>
<value>classpath*:trace.properties</value>
<value>classpath*:message.properties</value>
</list>
</property>
</bean>
<!-- dataSource 配置 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${ds.initialSize}"/>
<property name="minIdle" value="${ds.minIdle}"/>
<property name="maxActive" value="${ds.maxActive}"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${ds.maxWait}"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/>
<property name="validationQuery" value="SELECT 'x' from dual"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="false"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat"/>
</bean>
<!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"
p:configLocation="classpath:mybatis-config.xml"
p:mapperLocations="classpath:com/datadriver/**/dao/*.xml;classpath:com/haikai/**/dao/*.xml"
>
<property name="plugins">
<array>
<bean class="com.datadriver.web.trace.interceptor.TraceInterceptor"/>
</array>
</property>
</bean>
<!-- spring与mybatis整合配置,扫描所有dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
p:basePackage="com.datadriver.web.*.dao;com.datadriver.web.*.*.dao;com.datadriver.web.*.bo;com.haikai.web.tp.*.dao;com.haikai.web.tp.*.*.dao;com.haikai.web.tp.*.*.*.dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
<!--<!– 对dataSource 数据源进行事务管理 –>-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- 异步线程池 -->
<bean id="taskExecutor" name="taskExecutor"
class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="20"/>
<!-- 最大线程数 -->
<property name="maxPoolSize" value="50"/>
<!-- 队列最大长度 >=mainExecutor.maxSize -->
<property name="queueCapacity" value="50"/>
<!-- 线程池维护线程所允许的空闲时间 -->
<property name="keepAliveSeconds" value="3000"/>
<!-- 线程池对拒绝任务(无线程可用)的处理策略 -->
<property name="rejectedExecutionHandler">
<bean class="java.util.concurrent.ThreadPoolExecutor$CallerRunsPolicy"/>
</property>
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory"/>
</bean>
<bean id="sqlMapper" class="com.github.abel533.sql.SqlMapper">
<constructor-arg ref="sqlSession"/>
</bean>
</beans>
使用spring注解的配置方式:
@Configuration
@PropertySource("classpath:jdbc.properties")
public class JdbcConfig {
@Value("${jdbc.driverClassName}")
String driverClassName;
@Value("${jdbc.url}")
String url;
@Value("${jdbc.username}")
String username;
@Value("${jdbc.password}")
String password;
@Bean
public DruidDataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName(driverClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);
return dataSource;
}
}
使用springboot的配置方式:属性文件+属性类+配置类【不需要@value】
属性文件:application.properties
与spring的区别,@ConfigurationProperties注解,可以省略@value注解
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/springbootdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=123456
属性类:JdbcProperties.java
@ConfigurationProperties(prefix="jdbc") // 取出属性文件 jdbc开头的值注入给配置类中的属性
@PropertySource("application.properties") // 注入属性文件
@Data
public class JdbcProperties {
String driverClassName;
String url;
String username;
String password;
}
配置类:JdbcConfig.java
作用:通过属性类的对象配置数据源并注入spring容器
@Configuration
@EnableConfigurationProperties(JdbcProperties.class) // 注入属性类
public class JdbcConfig {
@Bean
@ConfigurationProperties
public HikariDataSource dataSource(JdbcProperties prop){
System.out.println(prop);
HikariDataSource dataSource = new HikariDataSource();
dataSource.setDriverClassName(prop.getDriverClassName());
dataSource.setJdbcUrl(prop.getUrl());
dataSource.setUsername(prop.getUsername());
dataSource.setPassword(prop.getPassword());
return dataSource;
}
}
简化:简化配置类
@Configuration
@EnableConfigurationProperties(JdbcProperties.class) // 注入属性类
public class JdbcConfig {
@Bean
@ConfigurationProperties(prefix = "jdbc") // 检查jdbc开头的属性,去DataSource类查找set
// 方法,如果有该set方法则注入属性值
public HikariDataSource dataSource(JdbcProperties prop){
return new HikariDataSource();
}
}
yaml文件格式
区别于properties文件的优势:可以注入集合、对象、数组
常见配置:
##拦截器拦截规则,拦截.do
server:
servlet:
path: "*.do"
port: 8088
##日志级别控制
logging:
level:
cn.wan: debug
#org.springframework: debug
#数据源配置,默认HiKariCP
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/springbootdemo?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
username: root
password: 123456
#试图解析器
mvc:
view:
prefix: /WEB-INF/views2/
suffix: .jsp
#mybatis
mybatis:
configuration:
map-underscore-to-camel-case: true #开启自动驼峰匹配
type-aliases-package: com.wan.pojo #别名,对应的实体类名字
mapper-locations: classpath:mapper/*.xml #扫描.xml文件,映射文件路径
在yaml里面配置属性,可以修改springboot默认启动类的属性值,
如果想修改类的实现不使用默认启动类,则配合@Bean使用
springboot默认@Bean
自定义启动器的编写