Spring全家桶之spring boot(二)

    spring boot的两种配置文件:

   虽然spring boot可以帮助我们进行一些配置项,但是有些内容还是需要开发者自己进行配置,因此spring boot提供了配置文件以供开发者配置。spring boot除了支持我们比较熟悉的properties文件之外,还支持yml格式的配置文件,默认是会创建properties格式的,这两个格式二选一即可。

   我们在配置文件中输入的时候会有提示,提示的数据是从这里获取的spring-configuration-metadata.json第三方技术基本都会提供这样的json数据到spring boot里面,这样子我们在配置文件中配置这些第三方技术的时候也会有提示。

    首先我们先创建一个controller

 1 package com.scm.properties.controller;
 2 
 3 import org.springframework.web.bind.annotation.GetMapping;
 4 import org.springframework.web.bind.annotation.RestController;
 5 
 6 @RestController
 7 public class HelloController {
 8     @GetMapping
 9     public String hello(){
10         return "hello";
11     }
12 }

    application.properties

     基本可以将所有支持spring boot相关技术的配置文件都统一配置到application.properties里面。即如果你想添加或修改一些配置的话,直接操作application.properites即可。

#修改内置tomcat端口号
server.port=8081
#设置项目上下文
server.servlet.context-path=/springboot

    这里我们修改了tomcat的端口号以及项目的上下文,修改之后我们可以访问http:localhost:8081/springboot/hello

    application.yml

    spring boot支持的另外一种配置文件的格式是yml类型的,编写的yml配置文件时候要注意缩进冒号后面要有空格,如果yml和properties两个配置文件都存在的话,properties优先级高。下面是yml中的格式,类似一棵树形结构,整体看上去要比properties简洁一些。

server:
 servlet:
    context-path: /springboot
  port: 9090

    多环境配置

   在实际工作中通常会有多个环境,例如开发环境,测试环境,生产环境,每个环境都有自己独特的配置内容,这样可以创建多个配置文件用来区分。

     分别创建application-dev.propertiesapplication-test.properties、application-online.properties三个配置文件代表三个开发环境

开发环境:application-dev.properties
测试环境:application-test.properties
生产环境:application-online.properties

    如果想切换到某个开发环境需要在applicaiton.properties主配置文件中添加如下语句:

#切换到开发环境下
spring.profiles.active=dev

    这样就激活了application-dev.properties配置文件,如果application.properties与application-dev.properties中出现了相同的配置,则application.properties主配置文件中会失效;例如:application.properties中存在server.port=9090, application-dev.properties中存在server.port=9091,则此时端口号应该是9091。

     自定义配置

      除了spring-configuration-metadata.json中写好的配置项之外,我们可以在application.properties配置文件中自定义写入一些配置项。为了避免乱码,统一指定为utf-8。

1 #字符编码位置要放到下面中文的上面,下面是指定字符编码
2 spring.http.encoding.charset=UTF-8
3 spring.http.encoding.enabled=true
4 spring.http.encoding.force=true
5 #自定义配置项
6 school.name=henu
7 school.address=China
8 school.age=10

     读取方式(一)使用使用@value注解,创建controller:

package com.scm.properties.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ConfigInfoController {
    @Value("${school.name}")
    private String name;//此处变量名不要求与application.properties配置文件中保持一致
    @Value("${school.address}")
    private String address;
    @Value("${school.age}")
    private int age;
    @GetMapping("/config")
    public String initConfig(){
        return name + "," + address + "," + age;
    }
}

     通过@Value注解就可以获取我们在配置文件中写入的自定义配置。

     读取方式(二) 单独编写一个配置类,然后在controller中使用@Autowired注解注入该配置类。

package com.scm.properties.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "school")
public class ConfigInfo {
    private String name;//此处声明的变量名要与application.properties配置文件中的保持一致
    private String address;
    private int age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

    @Component注解的作用就是将ConfigInfo类加入到spring容器中,这样我们就可以在controller中使用@AutoWired注解注入了。

    @ConfigurationProperties(prefix = "school")表示会从application.properties配置文件中读取以school开头的配置。

    注意:与@Value方式不同的一点是,这里我们在配置类中声明的私有变量name,address,age必须与配置文件中的一致,而@Value注解下的变量名不要求与配置文件中的一致。因为第二种方式我们在配置类中声明了ConfigurationProperties(prefix = "school"),spring boot会去配置文件中寻找以school为前缀,以我们声明的变量名为后缀的配置内容,所以第二种方式要保证声明的变量名与配置文件种的一致。第一种方式spring boot会直接寻找@Value中的${" "}内的参数,所以注解下的变量名不要求保持一致,只不过一般情况下都会保持一致。

    写完配置类之后,controller中代码如下:

 1 package com.scm.properties.controller;
 2 
 3 import com.scm.properties.config.ConfigInfo;
 4 import org.springframework.beans.factory.annotation.Autowired;
 5 import org.springframework.beans.factory.annotation.Value;
 6 import org.springframework.web.bind.annotation.GetMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 @RestController
10 public class ConfigInfoController {
11 
12     @Autowired
13     private ConfigInfo configInfo;//将配置类注入
14     @GetMapping("/config1")
15     public String initConfig1(){
16         return configInfo.getName()+","+configInfo.getAddress()+","+configInfo.getAge();
17     }
18 }

    controller完成之后测试成功即可。

    一般情况下常用第二种方式读取,因为如果我们添加的自定义配置较多,则要写很多的@Value注解,这样代码就会显得很乱,所以我们只需要将所有参数都写入一个自定义的配置类即可。

    外部配置文件

    对于第二种方式我们还可以定义外部配置文件。如果要编写很多自定义配置到application.properties中的话,就会导致该配置文件冗余了,此时我们可以自己定义一个配置文件将自定义配置写到这个配置文件中。比如在resources目录下创建一个school.properties配置文件,然后将自定义配置写入到school.properties中。接着在配置类上只需要再添加@PropertySource注解,将之前application.properties文件中的自定义配置删除,此时再运行,即可从外部自定义配置文件读取配置项了。

#school.properties配置类
school.name=henu
school.address=China
school.age=10

    此时ConfigInfo配置类上一共有三个注解,@PropertySource用于指定配置文件的位置。

@Component
@PropertySource(value = "classpath:school.properties")
@ConfigurationProperties(prefix = "school")

     

    spring boot中使用JSP

   spring boot中没有直接支持jsp,官方建议使用thymeleaf、freeMarker模板作为前端的视图,不过我们可以通过配置来使用jsp。要想使用jsp首先就是要pom.xml中添加相关的依赖:

<!--引入Spring Boot内嵌的Tomcat对JSP的解析包-->
<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
<!-- servlet依赖的jar包start -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
</dependency>
<!-- servlet依赖的jar包end -->

<!-- jsp依赖jar包start -->
<dependency>
    <groupId>javax.servlet.jsp</groupId>
    <artifactId>javax.servlet.jsp-api</artifactId>
    <version>2.3.1</version>
</dependency>
<!-- jsp依赖jar包end -->

<!--jstl标签依赖的jar包start -->
<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>jstl</artifactId>
</dependency>
<!--jstl标签依赖的jar包end -->

    在spring boot中默认的视图解析器为html,所以在这里我们要将视图解析器的改为jsp,在application.properties配置文件中添加如下代码:

spring.mvc.view.prefix=/
spring.mvc.view.suffix=.jsp

    我们说过spring boot中不是直接支持jsp的,所以我们还需要在pom.xml的<build>标签内添加如下配置:

<resources>
        <resource>
            <directory>src/main/java</directory>
            <includes>
                <include>**/*.xml</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/resources</directory>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
        <resource>
            <directory>src/main/webapp</directory>
            <targetPath>META-INF/resources</targetPath>
            <includes>
                <include>**/*.*</include>
            </includes>
        </resource>
    </resources>

    上述三个resource标签分别表示将src/main/java下所有的.xml文件编译到target目录下、将src/main/resources下的所有文件编译到target目录下、将src/main/webapp(webapp需要手动创建、我们将创建的jsp文件都放在这个目录)下的jsp文件编译到META-INF/resources下。改配置主要是将jsp编译到META-INF里面,这样就可以访问到jsp了。

    在src/main/webapp下创建test.jsp文件

<%@ page contentType="text/html;charset=UTF-8" language="java" pageEncoding="utf-8" %>
<html>
    <body>
    <h2>Hello World!</h2>
    ${msg}
    </body>
</html>

    最后创建一个controller

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class JspController {

    @RequestMapping("/jsp")
    public String jsp(Model model) {
        model.addAttribute("msg", "hello JSP");
        return "test";
    }
}

    访问http://localhost:8080/jsp,到此为止spring boot中创建jsp已经全部完成。

原文地址:https://www.cnblogs.com/scm2019/p/11328810.html