《SpringBoot+Vue》Chapter02_Spring

2023-11-29  本文已影响0人  So_ProbuING

不使用spring-boot-starter-parent

spring-boot-starter-parent主要提供了如下默认配置:

<dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>3.0.0</version>
            </dependency>
        </dependencies>
    </dependencyManagement>

这样就可以不用继承spring-boot-starter-parent,需要配置一下Java的版本、编码格式

 <build>
        <plugins>
            <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>
        </plugins>
    </build>

@SpirngBootApplication

由三个注解组成

  1. @SpringBootConfiguration
    这个注解是一个@Configuration所以@SpringBootConfiguration的功能就是表明这是一个配置类。开发者可以在这个类中配置Bean。
  2. @EnableAutoConfiguration
    表示开启自动化配置,SpringBoot中的自动化配置时非侵入的,在任意时刻,开发者都可以使用自定义配置代替自动化配置中的某一个配置
  3. @ComponentScan表示包扫描

Properties配置

SpringBoot中采用了大量的自动化配置。需要自己手动配置,承载这些自定义配置的文件就是resources目录下的application.properties文件
SpringBoot项目中的application.properties配置文件一共可以出现在如下位置:

类型安全配置属性

Spring提供了@Value注解以及EnvironmentAware接口欧来将SpringEnvironment中的数据注入到属性上,在application.properties中添加

book.name=bookName
book.author=luoguanzhong
book.price=100

@Component
@ConfigurationProperties(prefix = "book")
public class Book {
    private String name;
    private String author;
    private Integer price;
..省略getter/setter
}
@RestController
public class BookController {
    @Autowired
    private Book book;
    @GetMapping("/book")
    public String book() {
        return book.toString();
    }
}

YAML配置

常规配置

YAML是JSON的超集,简洁而强大,是专门用来书写配置文件的语言,可以替代application.properties。spring-boot-starter-web依赖会简介地引入了snakeyaml依赖,snakeyaml会实现对YAML配置的解析。

server:
  port: 8081
  servlet:
    context-path: /chapter02
  tomcat:
    uri-encoding: utf-8

复杂配置

YAML不仅可以配置常规属性,也可以配置复杂属性

book:
  name: yamlName
  author: bookAuthor
  price: 22

配置数组

book:
  name: yamlName
  author: bookAuthor
  price: 22
  kind:
    - a1
    - a2
    - a3

Book中

 private List<String> kind;

    @Override
    public String toString() {
        return "Book{" +
                "name='" + name + '\'' +
                ", author='" + author + '\'' +
                ", price=" + price +
                ", kind=" + kind +
                '}';
    }

    public List<String> getKind() {
        return kind;
    }

    public void setKind(List<String> kind) {
        this.kind = kind;
    }

Profile

创建配置文件

在resources目录下创建两个配置文件:application-dev.properties、application-prod.properties

配置application.properties

spring.profiles.active=dev

这个表示使用application-dev.properties配置文件启动项目,若将dev改为prod则表示使用application-prod.properties启动项目

上一篇 下一篇

猜你喜欢

热点阅读