springBoot
springBoot
spring和springboot
慕课网免费视频(尽快观看,可能随时收费) https://www.jianshu.com/p/157328066dfbhttps://www.imooc.com/learn/1314https://www.imooc.com/learn/956https://www.imooc.com/learn/1058https://blog.didispace.com/spring-boot-learning-2x/
SpringBoot使用@Scheduled创建定时任务
https://blog.csdn.net/qidasheng2012/article/details/84386662
1.主程序入口 Application 添加注解
@EnableScheduling2.实体添加注解
@Component
注解 @MapperScan
package com.yuan.springbootssm;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import springfox.documentation.swagger2.annotations.EnableSwagger2;
@SpringBootApplication
@MapperScan("com.yuan.springbootssm.mapper")//自动扫描的Mapper包,如果这里不指定,则需要在每个Mapper接口中添加@Mapper主键(这两种方法二选一)
@EnableSwagger2 //开启Swagger2功能,方便测试RestApi
public class SpringbootSsmApplication {
public static void main(String[] args) {
SpringApplication.run(SpringbootSsmApplication.class, args);
}
}
配置:https://blog.csdn.net/weixin_36293915/article/details/112177543
spring 配置 常量
https://www.jianshu.com/p/57e8554b691e
首先有两个可以来配置的文件
.properties文件
.yml文件
关于.properties
如果用的是.properties文件时,在实体类*(或者说是javaBean)*上加上注解@Configuration & @PropertySource("classpath:xxxxxx.properties") & @ConfigurationProperties(prefix = "xxx.yyy")
@propertySource: classpath来加载配置文件的位置。
@ConfigurationProperties(prefix="xxx.yyy"):就是在xxx.yyy的后面是要配置的属性
关于.yml
如果用的是.yml文件时,如果是在appliction.yml上,如果要读取属性值,只需要加@Value("${属性名}")
如果要将属性赋值给JavaBean时, 先将JavaBean中的属性对应然后再加上注解@ConfigurationProperties(prefix="xxyy")
最好再添加上@Component组件
@ConfigurationProperties(prefix="xxyy") : xxyy就是.yml文件中要对这个javabean中的配置
应用类或者Application类
加上@EnableConfigurationProperties({xxxxxx.class})
注意:jar包
用maven中的pom文件来加入jar包
<dependency>
<groupId> org.springframework.boot </groupId>
<artifactId>spring-boot-configuration-processor</artifactId>
<optional>true</optional>
</dependency>
案例;
在application.yml中添加配置(注意my 前面不能有空格否在报错:java.lang.IllegalStateException: Failed to load property source from location 'classpath:/applicatio)
##==================自定义常量=============
my:
# 注释
name: forezp
age: 12
number: ${random.int}
uuid : ${random.uuid}
max: ${random.int(10)}
value: ${random.value}
greeting: hi,i'm ${my.name}
使用
@Value("${my.name}")
private String name;
@Value("${my.age}")
private int age;
@RequestMapping(value = "/miya")
public String miya1() {
return name+":"+age;
}
https://blog.csdn.net/baidu_39298625/article/details/98102453https://blog.csdn.net/u013248535/article/details/55100979 打jar https://blog.csdn.net/ooyhao/article/details/82898973
application.yml文件配置(oracle)
https://fiend.blog.csdn.net/article/details/104768349
server.port=8080
server.tomcat.uri-encoding=utf-8
#Oracle
spring.datasource.driver-class-name=oracle.jdbc.driver.OracleDriver
spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521:orcl
spring.datasource.username=CPMS_DEV
spring.datasource.password=CPMS_DEV
#MySQL
#spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
#spring.datasource.url=jdbc:oracle:thin:@127.0.0.1:1521/orcl
#spring.datasource.username=****
#spring.datasource.password=****
搭建好springboot 测试时,需要注意,如果不加 @ResponseBody 则表示跳转视图,需要配置mvc
@RequestMapping("/index")
public String sayHello(){
return "index";
}
/**
* 需要加 @ResponseBody
* 否则 跳视图,需要配置 mvc
* mvc:
* view:
* prefix: /WEB-INF/jsp/
* suffix: .jsp
* static-path-pattern: /static/**
* @return
*/
@ResponseBody
@RequestMapping(value = "text")
String text(){
return "Hello World!";
}
jar 运行
项目打包jar
## cmd 到目录下
java -jar test2-0.0.1-SNAPSHOT.jar
java -jar test2-0.0.1-SNAPSHOT.jar --server.port=8082

指定java,利用较本启动
[程序打包jar 启动-指定jdk.bat](other\程序打包jar 启动-指定jdk.bat)
SpringBoot - 读取JSON文件
https://www.cnblogs.com/maggieq8324/p/15227236.html
JsonUtil.java
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.io.Reader;
public class JsonUtil {
/**
* 读取JSON文件转换为字符串
* @param filePath
* @return
*/
public static String readJsonFile(String filePath) {
String jsonStr = "";
try {
File jsonFile = new File(filePath);
Reader reader = new InputStreamReader(new FileInputStream(jsonFile), "utf-8");
int ch = 0;
StringBuffer sb = new StringBuffer();
while ((ch = reader.read()) != -1) {
sb.append((char) ch);
}
reader.close();
jsonStr = sb.toString();
return jsonStr;
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
}
- fastjson
<!-- fastjson -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.48</version>
</dependency
- 对象形式读取转换
String jsonStr = JsonUtil.readJsonFile("src/main/resources/json/xxx.json");
JSONObject result = JSONObject.parseObject(jsonStr);
- 数组形式读取转换
String jsonStr = JsonUtil.readJsonFile("src/main/resources/json/xxx.json");
JSONArray result = JSONObject.parseArray(jsonStr);
Druid 内置Filter配置,导致 mybatis 无法批量插入
Spring Boot配置druid连接池,进行批量插入,
需要设置过滤器 WallFilter 的配置: WallConfig 的参数 multiStatementAllow 为true,默认情况下false不允许批量操作
解决:java.sql.SQLException: sql injection violation, multi-statement not allow
- 方式一
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
# filters: stat,wall
filter:
#配置StatFilter (SQL监控配置)
stat:
enabled: true #开启 SQL 监控
slow-sql-millis: 1000 #慢查询
log-slow-sql: true #记录慢查询 SQL
#配置WallFilter (防火墙配置)
wall:
enabled: true #开启防火墙
config:
update-allow: true #允许更新操作
drop-table-allow: false #禁止删表操作
insert-allow: true #允许插入操作
delete-allow: true #删除数据操作
multi-statement-allow: true #批量数据操作
- 方式2
package com.ejudata.platform.config;
import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.List;
@Configuration
public class DruidConfig {
//使用连接池dataSource
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource druidDataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
List<Filter> filterList = new ArrayList<>();
filterList.add(wallFilter());
druidDataSource.setProxyFilters(filterList);
return druidDataSource;
}
@Bean
public WallFilter wallFilter() {
WallFilter wallFilter = new WallFilter();
wallFilter.setConfig(wallConfig());
return wallFilter;
}
@Bean
public WallConfig wallConfig() {
WallConfig config = new WallConfig();
config.setMultiStatementAllow(true);//允许一次执行多条语句
config.setNoneBaseStatementAllow(true);//允许非基本语句的其他语句
return config;
}
}
yml
配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*.xml注意 classpath 后面有个 * 否则 引用其他jar 包下的xml 文件无法找到
需要开启历史
activiti: db-history-used: true history-level: audit
# Spring
spring:
redis:
host: 192.168.2.156
port: 6379
database: 0
password: semdo123
timeout: 60s
lettuce:
pool:
max-idle: 30
max-active: 8
max-wait: 10000
min-idle: 10
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://192.168.2.156:3306/yjydxj-cloud?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8&allowMultiQueries=true
username: root
password: Semdo@2021
type: com.alibaba.druid.pool.DruidDataSource
druid:
web-stat-filter:
enabled: true
url-pattern: "/*"
exclusions: "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*"
stat-view-servlet:
login-username: admin
login-password: admin
enabled: true
allow: ""
url-pattern: /druid/*
#初始化链接数量
initialSize: 5
#最小空闲链接数
minIdle: 10
#最大并发连接数
maxActive: 50
#获取链接等待超时的时间
maxWait: 60000
#配置间隔多久才进行一次检测,检测需要关闭的空闲链接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
#申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。
testWhileIdle: true
#配置从连接池获取连接时,是否检查连接有效性,true每次都检查;false不检查。做了这个配置会降低性能。
testOnBorrow: true
#配置向连接池归还连接时,是否检查连接有效性,true每次都检查;false不检查。做了这个配置会降低性能。
testOnReturn: true
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 300000
# 配置一个连接在池中最大生存的时间,单位是毫秒
# maxEvictableIdleTimeMillis: 900000
# 配置检测连接是否有效
validationQuery: SELECT 1 FROM DUAL
#打开PsCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
#合并多个DruidDatasource的监控数据
useGlobalDataSourceStat: true
#通过connectProperties属性来打开mergesql功能罗慢sQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500;
# 超过时间限制是否回收
removeAbandoned: true
# 当连接超过3分钟后会强制进行回收
removeAbandonedTimeout: 180
activiti:
db-history-used: true
history-level: audit
# Mybatis配置
mybatis:
# 搜索指定包别名
typeAliasesPackage: cn.semdo.qxdanger,cn.semdo.activiti
# 配置mapper的扫描,找到所有的mapper.xml映射文件
mapperLocations: classpath*:mapper/**/*.xml
# swagger 配置
swagger:
title: demo接口文档
license: Powered By sys
licenseUrl: https://sys.iot
authorization:
name: sys OAuth
auth-regex: ^.*$
authorization-scope-list:
- scope: server
description: 客户端授权范围
token-url-list:
- http://localhost:8080/auth/oauth/token