Springboot的配置文件

一、给属性赋值

  • 使用原生的注解,@value,加载properties文件

  • 使用springboot,

    1
    2
    @Component
    @ConfigurationProperties(prefix = "person")//批量的注入配置
1.application.yaml
1
2
3
4
5
6
7
8
9
person:
name: 莫松
age: 3
map: {
K1: V1,
K2: V2
}
date: 2020/9/13
list: [ 1,2,3 ]
2.Person.java
1
2
3
4
5
6
7
8
9
10
11
12
@Component
@ConfigurationProperties (prefix = "person")
@AllArgsConstructor
@Data
@NoArgsConstructor
public class Person {
private String name;
private int age;
private Map<String, Object> map;
private List<Integer> list;
private Date date;
}

优点:

  • 可以使用松散绑定,就是自动匹配的属性不一定要是完全一样的例如在yaml里面可以使用first-name来与类的属性的firstName进行一个匹配;
二、JSR303校验

依赖

1
2
3
4
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>

validation的支持;

不然没有@Emai注解

二、使用yaml配置多套环境

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
person:
name: 2433
age: 3
map: {
K1: V1,
K2: V2
}
date: 2020/9/13
list: [ 1,2,3 ]
spring:
profiles:
active: test
---
server:
port: 8081
spring:
profiles: dev

---
server:
port: 8083
spring:
profiles: test

使用====分开每一套环境;在使用的时候就用spring:profiles:active: test来选择使用哪套环境,可以使用多套配置

三、静态资源路径

可以放的路径有

1
2
3
4
5
6
7
8
9
10
11
12
13
public WebMvcAutoConfigurationAdapter(ResourceProperties resourceProperties, WebMvcProperties mvcProperties,
ListableBeanFactory beanFactory, ObjectProvider<HttpMessageConverters> messageConvertersProvider,
ObjectProvider<ResourceHandlerRegistrationCustomizer> resourceHandlerRegistrationCustomizerProvider,
ObjectProvider<DispatcherServletPath> dispatcherServletPath,
ObjectProvider<ServletRegistrationBean<?>> servletRegistrations) {
this.resourceProperties = resourceProperties;
this.mvcProperties = mvcProperties;
this.beanFactory = beanFactory;
this.messageConvertersProvider = messageConvertersProvider;
this.resourceHandlerRegistrationCustomizer = resourceHandlerRegistrationCustomizerProvider.getIfAvailable();
this.dispatcherServletPath = dispatcherServletPath;
this.servletRegistrations = servletRegistrations;
}

这段代码就是说如果你配置了webmvc的话,就会把你的地址作为静态资源的路径;

这里的路径分别是ResourceProperties resourceProperties, WebMvcProperties mvcProperties

WebMvcProperties mvcProperties包含的WebMvcAutoConfiguration找到的是第一个:

第一个:

1
2
3
4
5
if (!registry.hasMappingForPattern("/webjars/**")) {
customizeResourceHandlerRegistration(registry.addResourceHandler("/webjars/**")
.addResourceLocations("classpath:/META-INF/resources/webjars/")
.setCachePeriod(getSeconds(cachePeriod)).setCacheControl(cacheControl));
}

/webjars/**;

其他的4个:在第二个ResourceProperties resourceProperties里面的

在ResourceProperties.java 里面可以找到

1
2
private static final String[] CLASSPATH_RESOURCE_LOCATIONS = { "classpath:/META-INF/resources/",
"classpath:/resources/", "classpath:/static/", "classpath:/public/" };

这里可以知道他的四个路径,并且随着优先级的顺序是

resource>static>public

根据习惯我们一般会把静态资源放在static目录下

==查看自动装配原理原码的规律:==

  • 一般先根据你要找的属性(可以直接ctrl+右键进入),找一个xxxxProperties.java,里面一般就是我们的属性的初始值
  • 你要知道他是如何自动装配的就要看xxxxPropertiesautoConfiguration.java,里面也有一些自动装配的东西

四、设置主页

主页放置的位置就是和静态资源的目录一样;

使用模板引擎以后,我们的每一个页面都要走这个模板引擎,哪怕是主页

五、模板引擎thymeleaf

导入的依赖:

1
2
3
4
5
6
7
8
9
10
11
12
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-java8time</artifactId>
</dependency>
<dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring5</artifactId>
</dependency>

在这里你可以明白一个寻找依赖的方式,就是寻找他的xxxxProperties.java和xxxxPropertiesautonconfiguration.java如果爆红可能就说明你的有些依赖还是没有导入进来;我们就需要知道那些没导入,在对我们的依赖导入;spring boot的自动装配不代表他可以装配你没有的东西;

原理:

thymeleafProperties.java:

1
2
3
4
5
private static final Charset DEFAULT_ENCODING = StandardCharsets.UTF_8;

public static final String DEFAULT_PREFIX = "classpath:/templates/";

public static final String DEFAULT_SUFFIX = ".html";

表明了我们的网页要放在哪一个地方;

controller:

1
2
3
4
5
6
7
8
9
10
11
12
13
package com.saxon.springboot.Controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class HelloWorld {
@GetMapping("/hello")
public String helloworld(){
return "hello";
}
}

thymeleaf的头文件:

1
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

添加这个可以使用thymeleaf的标签

六、扩展springmvc配置

image-20200928215614613

不可以使用@EnableWebMvc不然的话,他的自动装配类就不可以使用,原码如下

WebMvcAutoConfiguration原码如下

1
2
3
4
@Configuration(proxyBeanMethods = false)
@ConditionalOnWebApplication(type = Type.SERVLET)
@ConditionalOnClass({ Servlet.class, DispatcherServlet.class, WebMvcConfigurer.class })
@ConditionalOnMissingBean(WebMvcConfigurationSupport.class)

@EnableWebMvc源码如下:

1
2
3
4
5
6
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
@Import(DelegatingWebMvcConfiguration.class)
public @interface EnableWebMvc {
}

DelegatingWebMvcConfiguration的源码:

1
2
3
4
5
6
7
8
9
@Configuration(proxyBeanMethods = false)
public class DelegatingWebMvcConfiguration extends WebMvcConfigurationSupport {
private final WebMvcConfigurerComposite configurers = new WebMvcConfigurerComposite();
@Autowired(required = false)
public void setConfigurers(List<WebMvcConfigurer> configurers) {
if (!CollectionUtils.isEmpty(configurers)) {
this.configurers.addWebMvcConfigurers(configurers);
}
}

查看原码我们可以知道,如果我们一旦使用了@EnableWebMvc注解那么原来的配置就会失效;

我们要扩展springmvc的话,我们就需要知道WebMvcProperties里面的配置,我们自写的类,一旦继承WebMvcConfigurer,并且复写了WebMvcProperties里面的属性的话,那么这个我们自定义的类的属性就会覆盖原来的类的属性,达到一个自己配置springmvc的目的;

视图解析跳转:实现了WebMvcConfigurer接口

1
2
3
4
5
6
7
    //视图解析viewcontroller
@Override
public void addViewControllers (ViewControllerRegistry registry) {
registry.addViewController ("/").setViewName ("index");
registry.addViewController ("/index.html").setViewName ("index");
}
addViewController ("/index.html"):表示你地址显示的位置;setViewName ("index")实际上的文件名字;

七、国际化

文件的层次

image-20200928150536161

1
2
3
4
5
spring:
thymeleaf:
cache: false
messages:
basename: i18n.login

为了防止出现乱码 ,我们要在application.yaml里面配置一下文件

引用配置文件的格式:

1
2
3
4
1.直接使用 
th:text="#{password}
2.使用[[#{标签(配置文件名)}]]
<button class="btn btn-lg btn-primary btn-block" type="submit">[[#{login.tip}]]</button>

image-20200928210158025

我们可以模仿着写一个、

image-20200928210244992

关于国际化需要用到的类,在这里进行一个说明

image-20200928213725828

它有3个构造方法,我们very容易就知道他的意思;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package com.saxon.springboot.config;

import org.springframework.context.annotation.Bean;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Locale;


public class i18n implements LocaleResolver {
@Override
public Locale resolveLocale (HttpServletRequest request) {
Locale locale = Locale.getDefault ();
String language = request.getParameter ("l");
System.out.println ("language==============>"+language);
if (! StringUtils.isEmpty (language)) {
String[] split = language.split ("_");
locale = new Locale (split[0], split[1]);
}
return locale;
}

@Override
public void setLocale (HttpServletRequest request, HttpServletResponse response, Locale locale) {

}
}

在springmvc(自己写的)中配置

1
2
3
4
5
//国际化
@Bean
public LocaleResolver localeResolver () {
return new i18n ();
}

你要修改那个配置,要么就继承方法,要么就自己写一个,但是需要注意的是,我们的方法名和类型要和你要修改的配置一致,不然无法自动装配例如我们要修改的就是localeResolver那么就不要再前面或者后面添加字母;

跳转携带参数:使用@{ ** **/路径(参数)}

1
2
<a class="btn btn-sm" th:href="@{/index.html(l='zh_CN')}">中文</a>
<a class="btn btn-sm" th:href="@{/index.html(l='en_US')}">English</a>

配置文件:

image-20200928222003811

结果示意:

zh_CN:

image-20200928222106161

en_US

image-20200928222141490

配置文件的自我切换,实现国际化;

八、配置拦截器

和我们以前所学的一样,区别就在与现在我们自己配置;

1
2
3
4
5
6
@Override
public void addInterceptors (InterceptorRegistry registry) {
registry.addInterceptor (new myInterceprter ())
.addPathPatterns ("/**") //添加拦截的路径
.excludePathPatterns ("/index.html","/login","/");//通过的请求
}
1
2
3
4
5
6
7
8
9
10
public class myInterceprter implements HandlerInterceptor {
@Override
public boolean preHandle (HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (request.getSession ().getAttribute ("user")!=null){
return true;
}
return false;
}

}

使用session;