(二)Spring Boot 基础配置

一、不使用spring-boot-start-parent

spring-boot-starter-parent 虽然方便,但是读者在公司中开发微服务项目或者多模块项目时一般需要使用公司自己的 parent 这个时候如果还想进行项目依赖版本的统一管理,就需要使用dependencyManagment 来实现了。添加如下代码到 pom.xm 文件中

<dependencyManagement>
   <dependencies>
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-depedencies</artifactId>
         <version>2.0.4.RELEASE</version>
         <type>pom</type>
         <scope>import</scope>
      </dependency>
   </dependencies>
</dependencyManagement>

此时,就可以不用继承 spring-bo ot starter-parent 了,但是 Java 的版本、编码的格式等都需要开发者手动配置。 Java 版本的配置很简单,添加一个 plugin 即可:

<plugin>
   <groupId>org.apache.maven.plugins</groupId>
   <artifactId>maven-compiler-plugin</artifactId>
   <version>3.1</version>
   <configuration>
       <source>1.8</source>
       <target>1.8</target>
   </configuration>
</plugin>

编码格式:

 <properties>
     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
     <project.reporting.outputEncodin>UTF-8</project.reporting.outputEncodin>
 </properties>

二、@SpringBootApplication

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = { @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
		@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {
}

@SpringBootApplication由三个注解组成

  • @SpringBootConfiguration

@Configuration
public @interface SpringBootConfiguration {
}

原来就是 个@Configuration ,所以@SpringBootConfiguration的功能就是表明这是 个配置类,开发者可以在这个类中配置 Bean。从这个角度来讲,这个类所扮演的角色有点类似于 Spring中 aplicationContext.xml 文件的角色。

  • @EnableAutoConfiguration
    表示开启自动化配置。 Spring Boot 中的 自动化配置是非侵入式的,在任意时刻,开发者都可以使用自定义配置代替自动化配中的某个配置。
  • @ComponentScan
    完成包扫描,也 Spring 中的功能。由于@ComponentScan注解默认扫描的类都位于当前类所在包的下面,因此建议在实际项目开发中项目启动类放在根包中。

虽然项目的启动类也包含@Configuration注解,但是开发者可以创建一个新的类专门用来配置Bean ,这样便于配置管理。这 类只需要上@Configuration注解即可。

@Configuration
public Class MyConfig {
}

项目启动类中的@ComponentScan注解,除了扫描 @Service@Repository@Component@Controller@RestController等之外 ,也会扫描@Configuration注解的类。

三、定制 banner

在这里插入图片描述
       Spring Boot 项目在启动时会打印一个banner,这个 banner 是可以定制的,在sources 目录下创建 banner.txt 文件,在这个文件中写入的文本将在项目启动时打印出来 如果想将 TXT 文本设成艺术字体,有以下几个在线网站可供参考

想关闭 banner 是可以的, 修改项目启动类 main 方法,

 public static void main(String[] args) {
 	SpringApplicationBuilder builder = new  SpringApplicationBuilder(SpringbootWebApplication.class);
    builder.bannerMode(Banner.Mode.OFF).run(args);
 }

四、Web 容器配置

4.1 Tomcat 配置

4.1.1 常规配置

       在Sprin Boot 中,可以内置Tomcat、Jetty、 Undertow、Netty等容器。当开发者添加了spring-boot-starter-web 依赖时认会使用 Tomcat 作为 Web 容器。 如果需要对 Tomcat 做进一步的配置,可以在 application.properties或者application.yml中进行配置

server:
  port: 8081
  error:
    path: /error
  servlet:
    session:
      timeout: 30m
    context-path: /start
  tomcat:
    uri-encoding: utf-8
    threads:
      max: 500
    basedir: /home/tmp

代码解释

  • server.port 配直了 Web 器的端口号。
  • error.path 配直了当项目出错时跳转去的页面
  • session .timeout 配置了 session 失效时间 30m 表示 30 分钟,如果不写单位 默认单位是秒,由于 Tomcat 中配直 session 过期时间以分钟为单位,因此这里单位如果是秒的话,该时间会被转换为一个不超过所配置秒数的大分钟数, 例如这里配置了119 ,默认单位为秒,则实际 session 过期时间为1分钟
  • context-path 表示项目名称,不配置时默认为/。如果配置了,就要在访问路径中加上配置的路径。
  • uri-encoding 表示配置 Tomcat 请求编码。
  • max threads 表示 Tomcat 最大线程数。
  • basedir 是一个存放 Tomcat 运行日志和临时文件的目录,若不配置,则默认使用系统的临时目录

4.1.2 https配置

       由于 HTTPS 具有良好的安全性,在开发中得到了越来越广泛的应用像微信公众号、小程序等的开发都要使用 HTTPS 来完成。对于个人开发者而言,一个 HTTPS 证书的价格还是有点贵,国内有一些云服务器厂商提供免费的 TTPS 证书,一个账号可以申请数个。不过在 jdk 中提供了Java 证书管理工具 keytool,在\jdk\bin 录下,通过这个工具可 以自己生成一个数字证书。生成命令如下:

keytool -genkey -alias tomcathttps -keyalg RSA -keysize 2048 -keystore sang.p12 -validity 365

命令解释
• -genkey 表示要创 一个新的密钥。
• alias 表示 keystore 的别名。
• keyalg 表示使用的加密算法是 RSA 种非对称加密算法
• -keysize 表示密钥的长度
• -keystore 表示生成的密钥存放位置
• validity 表示密钥的有效时间,单位为天

       在cmd 窗口中直接执行如上命令,在执行的过程中需要输入密钥口令等信息,根据提示输入即可。命令执行完成后,会在当前用户目录下生成一个名为 sang.pl2 的文件,将这个文件复制到项目的根目录下,然后在 application. yml 中做如下配置:

 server:
 	ssl:
	   key-store: sang.pl2
	   key-alias: tomcathttps
	   key-store-password: 123456

代码解释:

  • key-store 表示密钥文件名
  • key alias 表示密钥别名
  • key-store-password 就是在 cmd 命令执行过程中输入的密码
    配置成功后,启动项目,在浏览器中输入“ https://localhost:8081/start/hello” 来查看结果。注意,证书是自己生成的,不被浏览器认可,此时添加信任或者继续前进即可。
    在这里插入图片描述
    在这里插入图片描述

此时,如果以 HTTP 的方式访问接口,就会访问失败。
在这里插入图片描述

这是因为 Spring Boot 不支持同时在配置中启动 HTTP和HTTPS 。这个时候可以配置请求重定向,将 HTTP 请求重定向为 HTTPS 请求。配置方式如下:

import org.apache.catalina.Context;
import org.apache.catalina.connector.Connector;
import org.apache.tomcat.util.descriptor.web.SecurityCollection;
import org.apache.tomcat.util.descriptor.web.SecurityConstraint;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;


@Configuration
public class TomcatConfig {
    @Bean
    TomcatServletWebServerFactory tomcatServletWebServerFactory() {
        TomcatServletWebServerFactory factory = new TomcatServletWebServerFactory(){
            @Override
            protected void postProcessContext(Context context) {
                SecurityConstraint constraint = new SecurityConstraint();
                constraint.setUserConstraint("CONFIDENTIAL");
                SecurityCollection collection = new SecurityCollection();
                collection.addPattern("/*");
                constraint.addCollection(collection);
                context.addConstraint(constraint);
            }
        };
        factory.addAdditionalTomcatConnectors(createTomcatConnector());
        return factory;
    }
    private Connector createTomcatConnector() {
        Connector connector = new Connector("org.apache.coyote.http11.Http11NioProtocol");
        connector.setScheme("http");
        connector.setPort(8080);
        connector.setSecure(false);
        connector.setRedirectPort(8081);
        return connector;
    }
}

       这里首先配置一个 TomcatServletWebServerFactory ,然后添加一个 Tomca 中的Connector (监听8080 端口〉 请求转发到 8081 上去。
       配置完成后,在浏览器中输入“ http://localhost:8080/start/hello”,就会自动重定向到 https://localhost:8081/start/hello 上。

4.2 Jetty 配置

除了 Tomcat 外,也可以在 Spring Boot 中嵌入 Jetty ,配置方式如下:

<dependency>
   <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
    <exclusions>
        <exclusion>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-tomcat</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jetty</artifactId>
</dependency>

主要是从 spring-boot-starter-web 除去默认 Tomcat ,然后加入 Jeety 的依赖即可,此时启动项目,查看启动日志。
在这里插入图片描述

五、YAML配置

5.1 配置文件

       SpringBoot使用一个全局的配置文件,配置文件名称固定

  • application.properties
  • application.yml

配置文件的作用:修改SpringBoot自动配置的默认值;SpringBoot在底层都给我们自动配置好

5.2 配置文件属性注入

5.2.1 application.yml配置
person:
  lastName: hello
  age: 18
  boss: false
  birth: 2017/12/12
  maps: {k1: v1,k2: 12}
  lists:
    - music
    - code
    - games
  dogList[0]:
    name: 小狗
    age: 12
  dogList[1]:
    name: 小狗2
    age: 122
  dog:
    name: 小狗
    age: 12
5.2.2 定义实体类
/**
 * 将配置文件中配置的每一个属性的值,映射到这个组件中
 * @ConfigurationProperties:告诉SpringBoot将本类中的所有属性和配置文件中相关的配置进行绑定;
 *      prefix = "person":配置文件中哪个下面的所有属性进行一一映射
 * 只有这个组件是容器中的组件,才能容器提供的@ConfigurationProperties功能;
 **/
@Component
@ConfigurationProperties(prefix = "person")
public class Person {
    private String lastName;
    private Integer age;
    private Boolean boss;
    private Date birth;
    private Map<String, Object> maps;
    private List<String> lists;
    private List<Dog> dogList;
    private Dog dog;
    //提供get/set方法
}

@Component
class Dog{
    private String name;
    private Integer age;
    //提供get/set方法
}
5.2.3 使用@Resource或者@Autowired方式注入属性
@RestController
public class HelloController {
    @Resource
    Person person;

    @GetMapping("/hello1")
    public Person hello1() {
        return person;
    }
}

执行返回结果:
在这里插入图片描述

你可以引入依赖包,配置文件进行绑定时就会有提示

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-configuration-processor</artifactId>
    <optional>true</optional>
</dependency>

在这里插入图片描述

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值