一篇文章带你掌握主流办公框架——SpringBoot( 五 )

  1. 自定义对象封装指定数据
// 自定义对象Enterprise实现类(属于Domain)package com.itheima.domain;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;import java.util.Arrays;//封装yaml对象格式数据必须先声明当前实体类受Spring管控@Component//使用@ConfigurationProperties注解定义当前实体类读取配置属性信息,通过prefix属性设置读取哪个数据@ConfigurationProperties(prefix = "enterprise")public class Enterprise {private String name;private Integer age;private String tel;private String[] subject;@Overridepublic String toString() {return "Enterprise{" +"name='" + name + '\'' +", age=" + age +", tel='" + tel + '\'' +", subject=" + Arrays.toString(subject) +'}';}public String getName() {return name;}public void setName(String name) {this.name = name;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public String getTel() {return tel;}public void setTel(String tel) {this.tel = tel;}public String[] getSubject() {return subject;}public void setSubject(String[] subject) {this.subject = subject;}}// 服务层Controllerpackage com.itheima.controller;import com.itheima.domain.Enterprise;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.core.env.Environment;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestController@RequestMapping("/books")public class BookController {// 自动装配实现类即可@Autowiredprivate Enterprise enterprise;@GetMapping("/{id}")public String getById(@PathVariable Integer id){System.out.println(enterprise);return "hello , spring boot!";}}<!--实现自定义对象封装时会产生警告,我们需要添加以下依赖--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-configuration-processor</artifactId><optional>true</optional></dependency>SpringBoot多环境启动我们在开发过程中可能会采用不同的环境,频繁的转换环境当然不是一个好办法
SpringBoot选择配置多环境来控制环境选择启动
我们从两种不同的配置文件方向来讲解多环境:
  1. yaml多环境启动:
# yaml采用 --- 来表示环境层级更换 # yaml采用 spring:profiles:active: 环境id 设置启用的环境spring:profiles:active: dev---#开发环境#yaml采用 spring:config:activate:on-profile: 环境id 来定义当前环境id(规范写法)spring:config:activate:on-profile: dev#以下属于环境配置server:port: 80---#生产#yaml采用 spring:profiles: 环境id 来定义当前环境id(旧版写法,同样适用)spring:profiles: pro#以下属于环境配置server:port: 81---#测试#yaml采用 spring:profiles: 环境id 来定义当前环境id(旧版写法,同样适用)spring:profiles: test#以下属于环境配置server:port: 82---
  1. properties多环境启动:
# application.properties文件(环境主文件)#设置启用的环境spring.profiles.active=pro# application-dev.properties文件(环境配置文件)# 设置相关资源配置server.port=8080# application-pro.properties文件(环境配置文件)# 设置相关资源配置server.port=8081# application-test.properties文件(环境配置文件)# 设置相关资源配置server.port=8082SpringBoot前端多环境启动我们前面提及过SpringBoot的快速启动直接将jar包打包后发给前端就可以采用命令行启动服务器
但是我们的配置可能会导致更多的细节问题:
  1. 当我们的yaml出现中文注释时,需要将IDEA的encoding均设置为UTF-8

    经验总结扩展阅读