高扩展,高可用,高性能
第一个spring
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<version>2.3.4.RELEASE</version>
</parent>
<dependencies>
<dependency>
<!--web依赖-->
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<!--打包插件,去maven工具,clean,package,去target目录下,启动jar包,即可运行服务-->
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
主程序,启动类
package com.nextstep;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
SpringApplication.run(MainApplication.class,args);
}
}
controller
//@Controller
//@ResponseBody 整个类,都是相应字符
@RestController
public class HelloController {
@RequestMapping("/hello")
// @ResponseBody
public String hello(){
return "hello springboot";
}
}
总结:
1. @ResponseBody + @Controller = @RestController
2. maven 重写springboot 提供的jar包版本号 :查看spring-boot-dependencies的mysql版本号,在当前的maven配置文件中重写,
<properties>
<xxx.verxion>2.3</xxx.verxion>
</properties>
注册bean对象
package com.nextstep.config;
import com.nextstep.bean.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConfig {
@Bean
public Student student(){
return new Student("1",1);
}
}
@SpringBootApplication
public class MainApplication {
public static void main(String[] args) {
ConfigurableApplicationContext run = SpringApplication.run(MainApplication.class, args);
Student bean = run.getBean(Student.class);
System.out.println(bean.toString());
}
}
@ImortResource("classpath:xxx.xml")
sprintboot使用注解导入spring配置文件
@ConfigurationProperties 参数配置
@Component
@ConfigurationProperties(prefix = "pig")
public class Pig {
private String name;
private String status;
}
application.properties->
pig.name=pigName
pig.status=pigStatus
Main->
Pig pig = run.getBean(Pig.class);
System.out.println(pig.toString());
Pig{name='"pigName"', status='"pigStatus"'}
lombok
安装lombok 插件
引入lombok
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
在实体类中,即可直接使用
@Data //get set 方法
@ToString //toString 方法
@AllArgsConstructor //有参构造方法
@NoArgsConstructor //无参构造方法
@EqualsAndHashCode //equals hashcode 方法
@Slf4j //引入日志,后续可以直接使用log.error等方法
dev tools
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
</dependency>
按ctrl+f9 自动更新重启
spring Initailizr 快速创建项目,自动导入初始配置
资源文件夹
resource 目录下
MET-INF/resources
resources
public
static
静态资源访问路径:
默认访问路径 ip:端口/xxxx
但是因为有拦截器的存在,所以静态资源不能写根目录,故需要设置个静态路径
spring.mvc.static-path-pattern:/res/**
指定资源文件夹路径(默认有上方几个)静态资源访问路径
sprint.resources.static-locations:classpath:/static/**
例子:想访问resources/static/image/aa.png
如果设置静态资源访问路径,那么路径直接写image/aa.png
如果设置了静态资源访问路径,那么路径写 static/image/aa.png
spring boot 多环境配置,加载指定 application 文件
在实际开发中,可能存在多套配置,如何在切换配置文件?
1.(假设下面得文件后缀为yaml)
默认加载 application.yaml , 那么可以在 application.yaml 中配置
spring:
profiles:
active: test
欢迎页
存在静态资源路径下(resources/resources、resources/static、resources/public 等等)index.html 静态文件,或者 存在 /index的controller,都会被springboot 当成欢迎页
Rest 风格
rest风格需要配置
spring.mvc.hiddenmethod.filter.enabled=true
由于form 提交仅支持post get
那么,如果需要 delete ,put 请求的时候,需要将表单设置为post方式
并且写带一个名为 _method 的参数,参数值为【delete | put】
@RestController
public class PigController {
// @RequestMapping(value = "/pig",method = RequestMethod.DELETE)
@DeleteMapping("/pig")
public String pigDelete(){
return "delete-delete";
}
// @RequestMapping(value = "/pig",method = RequestMethod.GET)
@GetMapping("/pig")
public String pigQuery(){
return "get-query";
}
// @RequestMapping(value="/pig",method = RequestMethod.PUT)
@PutMapping("/pig")
public String pigUpdate(){
return "put-update";
}
// @RequestMapping(value="/pig",method = RequestMethod.POST)
@PostMapping("/pig")
public String pigAdd(){
return "post-save";
}
}
常用配置
编辑 application.properties
#关闭thymeleaf 模板缓存
spring.thymeleaf.cache=false
#修改项目访问地址
server.servlet.context-path=/xx
#修改项目访问端口
server.port=xx
#指定国际化文件所在目录
spring.messages.basename=i18n.login
#修改默认日期格式
spring.mvc.date-format=yyyy/MM/dd
#默认不支持put,delete等请求方式
spring.mvc.hiddenmethod.filter.enabled=true
#修改tomcat字符编码
server.tomcat.uri-encoding=UTF-8
常用注解
@RequestMapping 作用于类或方法,用于指定类或者方法访问路径
@RequestMapping(value = "/pig",method = RequestMethod.DELETE)
@DeleteMapping("/pig")
@PutMapping("/pig")
@GetMapping("/pig")
@PostMapping("/pig")
以上四个注解,与上第一个相同
@Controller action 层 处理请求
@ReuquestParam("name") 从request 中获取名为name 的参数
@GetMapping("/usr/{id}")
@PathVariable("id") 寓意,获取请求路径中的id
@RequestHead 获取请求头中的参数
@RequestParam 获取请求参数
@CookieValue
获取cookie 中的参数,可使用String ,也可使用Cookie 类 来接收,用法同上
public void test (@CookieValue("_ga") String _ga,@CookieValue("_ga") Cookie _ga);
@RquestBody
@RequestAttribute
获取请求参数中的值,例如以下情况
参数 Map ,Model ,request 共享同一个域
redirect:/ 重定向
forward:/ 转发
Inteceptor 拦截器
设置拦截器
注册拦截器
文件上传
springboot 默认配置了,单个文件上传最大大小,可能需要修改
spring.servlet.multipart.max-file-size=1MB #单个文件最大
spring.servlet.multipart.max-request-size=100MB #多个文件最大
<form action="/uploadFile" method="post" enctype="multipart/form-data">
姓名:<input type="text" name="name"><br>
头像:<input type="file" name="touxiang"><br>
生活照:<input type="file" multiple name="shenghuozhao"><br>
<input type="submit" value="保存">
</form>
@RequestMapping("/uploadFile")
public String uploadFile(@RequestParam("name")String name,
@RequestParam("touxiang")MultipartFile touxiang,
@RequestParam("shenghuozhao")MultipartFile[] shenghuozhao) throws IOException {
log.info("name:"+name);
if(!Objects.isNull(touxiang)){
touxiang.transferTo(new File("f://"+touxiang.getName()));
}
if(!Objects.isNull(shenghuozhao)){
for (int i = 0; i < shenghuozhao.length; i++) {
shenghuozhao[i].transferTo(new File("f://"+shenghuozhao[i].getName()+i));
}
}
return "index";
}
错误回显
在templates 中新建 error文件夹
即可在该文件夹下,存放错误页面,文件文件名规则:500.html,5xx.html,4xx.html,404.html
并且可以在页面使用模板语法,打印相关错误信息
链接数据库
<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.37</version>
</dependency>
@SpringBootTest
public class jdbcTest {
@Autowired
JdbcTemplate jdbcTemplate;
@Test
public void jdbc(){
Long i = jdbcTemplate.queryForObject("select count(*) from device",Long.class);
System.out.println(i);
}
}
用properties 方式写,会报错。反而用yaml 则不会,不知道为什么
spring:
datasource:
url: jdbc:mysql://41.98.231.252:3306/testr?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: root
password: 123456
driver-class-name: com.mysql.jdbc.Driver
整合Druid 数据池
1. 代码实现
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
/**
* druid数据源
*/
@Configuration
public class DataSourcesConfig {
/**
* 配置druid数据源
*/
@Bean
@ConfigurationProperties("spring.datasource")//从配置中加载数据库参数
public DataSource dataSource() throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setFilters("stat,wall");
return dataSource;
}
/**
* 配置druid监控页
*/
@Bean
public ServletRegistrationBean servletRegist(){
StatViewServlet statViewServlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> servletRegistration = new ServletRegistrationBean<>(statViewServlet,"/druid/*");
//druid 监控页登录账号密码
servletRegistration.addInitParameter("loginUsername","xzx");
servletRegistration.addInitParameter("loginPassword","123");
return servletRegistration;
}
/**
* WebStatFilter 用于采集web-jdbc关联的监控数据
*/
@Bean
public FilterRegistrationBean webStatFilter(){
WebStatFilter webStatFilter = new WebStatFilter();
FilterRegistrationBean<WebStatFilter> filterRegistration = new FilterRegistrationBean<>(webStatFilter);
filterRegistration.setUrlPatterns(Arrays.asList("/*"));
filterRegistration.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistration;
}
}
经过以上配置,即可使用 http://127.0.0.1:8080/druid/index.html 访问监控页面
2. 配置实现:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependency>
spring:
datasource:
url: jdbc:mysql://xxxx:3306/moni1tor12?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=UTC
username: admin
password: 123456
driver-class-name: com.mysql.jdbc.Driver
druid:
filters: stat,wall
aop-patterns: com.nextstep
stat-view-servlet:
enabled: true
login-username: xzx
login-password: 123
resetEnable: false
web-stat-filter:
enabled: true
urlPattern: /*
exclusions: '*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*'
filter:
stat:
slow-sql-millis: 1000
logSlowSql: true
enabled: true
wall:
enabled: true
整合mybatis
pom.xml
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.0</version>
</dependency>
注:注解和配置的方式可以混合使用
1.通过配置操作
application.yaml
mybatis:
mapper-locations: classpath:mapper/*.xml
configuration:
map-underscore-to-camel-case: true
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.nextstep.mapper.DeviceMapper">
<select id="count" resultType="int">
select count(id) from device
</select>
<select id="query" resultType="com.nextstep.entity.Device">
select * from device where id=#{id}
</select>
</mapper>
mapper.java
@Mapper
public interface DeviceMapper {
int count();
Device query(String id);
}
2. 通过注解方式
@Mapper
public interface DeviceMapper {
@Insert("insert into device(`id`,`name`,`remark`) values(#{id},#{name},#{remark})")
void insert(Device device);
}
MybatisPlus
<dependency>
<groupId>cn.ocoop.framework.mybatis.plugin</groupId>
<artifactId>mybatis-plugin-spring-boot-starter</artifactId>
</dependency>
@Mapper
public interface ConfigMapper extends BaseMapper<Config> {
}
则后续,可以直接使用BaseMapper提供的crud方法