开发工具:IDEA 2019
springboot版本:2.1.9
一、springboot2.x VS 1.x
基础环境升级
依赖组件升级
默认软件替换和优化
测试
新技术的引入
二、hello-world
利用IDEA工具创建springboot工程:springboot-demo
pom.xml文件添加依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
编写 Controller 内容创建 HelloController
@RestController
public class HelloController {
@RequestMapping("/hello")
public String hello() {
return "hello world";
}
}
运行启动类:DemoApplication
浏览器访问:http://localhost:8080/hello ,页面展示 hello world 。
三、自定义filter
Spring Boot 内置了一些 Filter,
比如,处理编码的 OrderedCharacterEncodingFilter 和请求转化的 HiddenHttpMethodFilter,也支持根据我们的需求来可以自定义 Filter。
自定义 Filter 有两种实现方式:(推荐使用第二个方案)
第一种是使用 @WebFilter,
第二种是使用 FilterRegistrationBean
以第二种为例:
1、实现 Filter 接口,实现其中的 doFilter() 方法;
public class MyFilter implements Filter {
public void init(){}
public void doFilter(ServletRequest request,ServletResponse ServletResponse,FilterChain chain){}
public void destroy(){}
}
2、添加 @Configuration 注解,将自定义 Filter 加入过滤链。
@Configuration
public class WebConfiguration {
@Bean
FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean registrationBean = new FilterRegistrationBean();
registrationBean.setFilter(new MyFilter());
registrationBean.addUrlPatterns("/*");
registrationBean.setName("MyFilter");
//当有多个过滤器时可以通过设置 Order 属性来决定它
registrationBean.setOrder(6);
return registrationBean;
}
}
四、读取配置文件两种方式:
在 application.properties 中自定义配置:
demo.name=xxxxx
从配置文件加载单个配置内容时:
1、在注入的字段上使用注解 @Value 即可
@Value("${demo.name}")
private String name;
2、定义对象接受多个配置项
class类上使用注解 @ConfigurationProperties (prefix="demo") 列如:
@Component
@ConfigurationProperties (prefix="demo")
public class Demo{
private String name;
}
表示以 demo 开头的属性会自动赋值到对象的属性中,比如,demo.name 会自动赋值到对象属性 name 中
五、自定义配置文件:
1、在 resources 目录下创建一个 my.properties 文件
my.name=test
my.password=test
2、定义对象接受配置项
类上使用注解 @PropertySource("classpath:my.properties") 读取配置文件
@Component
@ConfigurationProperties(prefix = "my")
@PropertySource("classpath:my.properties")
public class MyProperties {
private String name;
private String password;
//省略setter getter
}
原文:https://www.cnblogs.com/qq99514925/p/11568391.html