SpringBoot操作手册

82 阅读4分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 10 月更文挑战」的第17天,点击查看活动详情

SpringBoot 的配置文件

全局配置文件有两种格式,目录在 resource 文件夹下

  • application.properties
  • application.yml

yml 基本语法

  • k:(空格)v    表示一对键值对,其中空格是必须的
  • 以空格的缩进来控制层级关系,只要是左对齐的,就是同一个层级
  • 属性和值是大小写敏感的

键值对的几种形式

  1. 基本类型和字符串
  • 字符串默认不加单引号或者双引号
  • 双引号:不会转义字符
如输入"hello \n  world"    代表:"hello 换行  world"
  • 单引号:会转义字符
如输入'hello \n  world'   代表:"hello \n  world"
  1. 对象或 Map

第一种写法:

key:     name: zhangsan     age: 13

第二种写法:行内写法

key: {name: zhangsan,age: 13}
  1. 数组(Set,List)

第一种写法:用  -  值的方式

pets:    - cat    - dog    - pig

第二种写法:

pets: [dog,cat,pig]

将配置文件的内容和类匹配

有两种方式:

  • 第一种使用@ConfigurationProperties 注解
  • 第二种使用@Value 注解

区别:

如果觉得把配置信息都写在默认的 application.yml 中太多了,可以写在外部的文件中,这就需要使用@PropertySource 注解

@ConfigurationProperties(prefix = "person")
@PropertySource(value = {"classpath:person.properties"})

这样使用的就是 person.properties 中的值了

SpringBoot 中默认是没有 Spring 配置文件的,要想使用必须用@ImportResouce 导入

@ImportResource(locations = "bean.xml")

不过 SpringBoot 不建议使用配置文件来配置,而是推荐使用类和注解的方式,使用@Configration 声明这是配置类,@Bean 将对象加入到容器中

@Configuration public class Myconfige {

  //将方法返回值添加到容器,该方法的名称就是默认的id
  @Bean  
  public HelloService helloService(){
  return new HelloService();
  }
}

配置文件占位符

可以使用随机数

name: ${random.uuid}

可以使用占位符

summary: ${name}

多个配置文件环境的切换

如果是使用 properties 文件,可以写多个配置文件,格式为 application-{profile}.properties.然后在 application.properties 中选择激活其中一个如果是使用 yml 文件,可以写多个文档块,然后选择激活其中一个。

激活方式有两种:

  • spring.profiles.active 来指定
  • 或者命令行  --spring.profies.active=dev 以下是 yml 文件的示例:

spring:   
   profiles:
      active: prod
--- spring:   profiles: dev server:   port: 8083
--- spring:   profiles: prod server:   port: 8087

配置文件加载顺序

从上往下,最上面的优先级最高

在项目已经打包之后,还可以通过命令行 spring.confige.location 来指定配置文件位置

自动配置的原理

SpringBoot 的主程序中加了@SpringBootApplication 注解,这个注解里面包含了@EnableAutoConfiguration 注解,这个注解又包含了这个注解@Import({AutoConfigurationImportSelector.class})。这个类中有一个方法就是找 META-INF/spring.factories 文件,然后把这个文件里写的类都加载进来。 自动配置类只会在一定的条件下生效。在 application.yml 中设置 debug=true,可以打印出哪些自动配置类生效了

配置 JSON 的转换

在启动类中注入该 Bean 即可

@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
//1、定义一个convert转换消息的对象
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
//2、添加fastjson的配置信息
FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
//3、在convert中添加配置信息
fastConverter.setFastJsonConfig(fastJsonConfig);
//4、将convert添加到converters中
HttpMessageConverter<?> converter = fastConverter; return new HttpMessageConverters(converter); }

servlet 容器的配置

问题 1:修改配置

  • 第一种方式: 修改 servlet 的配置 通过在 application.properties 中的 server.xxx 来修改 修改 tomcat 配置 通过在 application.properties 中声明 server.tomcat.xxx 来修改
  • 第二种方式: 使用编码的方式:
@Bean
public ConfigurableServletWebServerFactory configurableServletWebServerFactory(){  
TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory();   

final TomcatConnectorCustomizer customizer=new TomcatConnectorCustomizer() {     
  @Override         
  public void customize(Connector connector) {   
  connector.setPort(8084);     
  }
  };   
  factory.addConnectorCustomizers(customizer);  
  return factory;
}

问题 2:注册三个组件

servlet

//自定义的Servlet
@Bean
public ServletRegistrationBean myservlet(){
ServletRegistrationBean servletRegistrationBean=new ServletRegistrationBean(new MyServlet(),"/servelet");
return servletRegistrationBean;
}

filter

//自定义拦截器
@Bean
public FilterRegistrationBean filterRegistrationBean(){
FilterRegistrationBean filterRegistrationBean=new FilterRegistrationBean();
filterRegistrationBean.setFilter(new MyFilter());  
filterRegistrationBean.setUrlPatterns(Arrays.asList("/filter"));  
return filterRegistrationBean; }

lister

ServletListenerRegistrationBean  同上

springboot 为我们自动配置的 spring mvc 的前端控制器就是用的前面这个方法。 源码在 DispatcherServletAutoConfiguration  类的 dispatcherServletRegistration 方法中

问题 3:切换其他的 servlet 容器

问题 4:使用外部的 servlet 容器

在 src/main 下面建立 webapp 文件夹 在 webapp 下建立 WEB-INF 文件夹,并放入 web.xml 文件 项目打包方式改为 war 包 项目中添加 tomcat,将嵌入式的 tomcat 的 scope 设置为 provided 编写一个 SpringBootServletInitializer 的子类,调用 configuer 方法。传入 springboot 应用的主程序

自动执行 sql 语句

  • 默认将文件命名为 schema-.sql  data-.sql 放在资源目录文件 resource 下,启动会自动执行
  • 或者指定 spring.datasource.schema

解决跨域问题

springboot 里面

  1. 在 config 里面继承 WebMvcConfigurationSupport 类,写如下代码
//处理跨域问题
@Override
public void addCorsMappings(CorsRegistry registry) {   
  registry.addMapping("/**").allowedOrigins("*") .allowedHeaders("*").allowedMethods("*").allowCredentials(true).maxAge(3600);
  }

如果上面生效不了的话在请求返回的时候加这段

response.setHeader("Access-Control-Allow-Origin","http://localhost:8081");
response.setHeader("Access-Control-Allow-Credentials""true");
response.setHeader("Access-Control-Allow-Methods""POST, GET, PATCH, DELETE, PUT");
response.setHeader("Access-Control-Max-Age""3600");
response.setHeader("Access-Control-Allow-Headers""Origin, X-Requested-With, Content-Type, Accept");

vue 里面

在 main.js 里面加

axios.defaults.withCredentials = true