[TOC]
访问spring.io官网,找到所有启动器列表
https://docs.spring.io/spring-boot/docs/2.1.0.BUILD-SNAPSHOT/reference/htmlsingle/#using-boot-starter
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<optional>true</optional>
</dependency>
intellij idea需要修改一些配置,详见https://blog.csdn.net/hz_940611/article/details/80594788
ctrl + F9 重新编译之后,重新访问
指定配置文件,对于只有一个yml配置文件,可以通过下面这种方式
spring:
profiles:
active: uat
---
server:
port: 8081
spring:
profiles: dev
---
server:
port: 8082
spring:
profiles: uat
spring-boot-autoconfigurate-xxx.release.jar
核心配置文件
org.slf4j.Logger
java.util.logging.Logger
org.apache.commons.logging.Log
配置文件映射到实体
@Component
@ConfigurationProperties(prefix = "student")
指定配置文件路径进行映射
@Configuration
@ConfigurationProperties(prefix = "com.user")
@PropertySource(value = "classpath:test.properties")
添加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
添加数据连接配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT
username: root
password: 123456
使用JdbcTemplate模板操作数据库
示例
jdbcTemplate.update("insert into account(name, money) values(?, ?)",
account.getName(),account.getMoney());
jdbcTemplate.query("select * from account where id = ?",
new Object[]{id},
new BeanPropertyRowMapper(Account.class));
添加依赖项
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
数据库连接配置
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT
username: root
password: 123456
jpa:
hibernate:
ddl-auto: update #第一次建表create 后面用update
show-sql: true
# 定义数据库引擎为innodb
database-platform: org.hibernate.dialect.MySQL5InnoDBDialect
定义实体类
@Entity
@Table(name = "t_account")
public class Account implements Serializable{
private static final long serialVersionUID = 4309084519412872386L;
@Id
@GeneratedValue
private int id ;
private String name ;
private double money;
//省略getter setter方法...
}
编写dao,继承JpaRepository接口
public interface AccountDao extends JpaRepository<Account,Integer> {
}
druid包含了mybatis的依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.29</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
配置数据库连接
略
编写Mapper文件
@Mapper
public interface AccountMapper {
@Insert("insert into account(name, money) values(#{name}, #{money})")
int add(@Param("name") String name, @Param("money") double money);
@Update("update account set name = #{name}, money = #{money} where id = #{id}")
int update(@Param("name") String name, @Param("money") double money, @Param("id") int id);
@Delete("delete from account where id = #{id}")
int delete(int id);
}
1)添加druid依赖
2)yml配置文件
spring:
datasource:
driver-class-name: com.mysql.jdbc.Driver
url: jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=gbk&zeroDateTimeBehavior=convertToNull&serverTimezone=GMT
username: root
password: 123456
mybatis:
#指明和数据库映射的实体的所在包
type-aliases-package: com.example.demo.entity
##指明mapper的xml文件存放位置
mapper-locations: classpath:mybatis/*.xml
3)Mapper.java
public interface AccountMapper {
int update( @Param("money") double money, @Param("id") int id);
}
4)Mapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.example.demo.mapper.AccountMapper">
<update id="update">
UPDATE account set money=#{money} WHERE id=#{id}
</update>
</mapper>
5)启动类扫描mapper包路径
@MapperScan("com.example.demo.mapper")
1)添加redis的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2)redis配置
spring.redis.host=localhost
spring.redis.port=6379
#spring.redis.password=
spring.redis.database=1
spring.redis.jedis.pool.max-active=8
spring.redis.jedis.pool.max-wait=-1
spring.redis.jedis.pool.max-idle=500
spring.redis..jedis.pool.min-idle=0
spring.redis.timeout=5000
3)StringRedisTemplate使用
@Autowired
private StringRedisTemplate template;
public void setKey(String key,String value){
this.template.opsForValue().set(key, value, 1, TimeUnit.MINUTES);//1分钟过期
}
public String getValue(String key){
return this.template.opsForValue().get(key);
}
<!--swagger2-->
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger2</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>io.springfox</groupId>
<artifactId>springfox-swagger-ui</artifactId>
<version>2.8.0</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>swagger-bootstrap-ui</artifactId>
<version>1.8.9</version>
</dependency>
swagger配置
@Configuration
@EnableSwagger2
public class Swagger2 extends WebMvcConfigurationSupport {
@Bean
public Docket createRestApi() {
return new Docket(DocumentationType.SWAGGER_2)
.apiInfo(apiInfo())
.select()
.apis(RequestHandlerSelectors.basePackage("com.example.demo.controller"))
.paths(PathSelectors.any())
.build();
}
private ApiInfo apiInfo() {
return new ApiInfoBuilder()
.title("springboot利用swagger2构建api文档")
.description("springboot利用swagger2构建api文档")
.termsOfServiceUrl("https://github.com/hejiancao/springboot")
.version("1.0")
.build();
}
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/swagger-ui.html")
.addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/doc.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/");
}
}
创建定时任务
// @Scheduled(fixedRate = 5000) :上一次开始执行时间点之后5秒再执行
// @Scheduled(fixedDelay = 5000) :上一次执行完毕时间点之后5秒再执行
// @Scheduled(initialDelay=1000, fixedRate=5000) :第一次延迟1秒后执行,之后按fixedRate的规则每5秒执行一次
// @Scheduled(cron=" /5 ") :通过cron表达式定义规则
@Scheduled(fixedRate = 5000)
public void reportCurrentTime() {
log.info("The time is now {}", dateFormat.format(new Date()));
}
启动类开启定时任务
@EnableScheduling
添加邮件依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
yml配置
spring.mail.host=aicev.icoremail.net
spring.mail.username=sen.shao@ai-ways.com
spring.mail.password=******
spring.mail.port=25
spring.mail.protocol=smtp
spring.mail.default-encoding=UTF-8
测试
@Autowired
private JavaMailSenderImpl mailSender;
private static final String SENDER = "sen.shao@ai-ways.com";
private static final String RECEIVER = "sen.shao@ai-ways.com";
/**
* 发送包含简单文本的邮件
*/
@Test
public void sendTxtMail() {
SimpleMailMessage simpleMailMessage = new SimpleMailMessage();
// 设置收件人,寄件人
simpleMailMessage.setTo(new String[] {RECEIVER});
simpleMailMessage.setFrom(SENDER);
simpleMailMessage.setSubject("Spring Boot Mail 邮件测试【文本】");
simpleMailMessage.setText("这里是一段简单文本。");
// 发送邮件
mailSender.send(simpleMailMessage);
System.out.println("邮件已发送");
}
更多....