赞
踩
SpringBoot中免除了大部分手动配置,但是对于一些特定的情况,还是需要我们进行手动配置的,SpringBoot为我们提供了application.properties配置文件,让我们可以进行自定义配置,来对默认的配置进行修改,以适应具体的生产情况,当然还包括一些第三方的配置。几乎所有配置都可以写到application.peroperties文件中,这个文件会被SpringBoot自动加载,免去了我们手动加载的烦恼。
SpringBoot可以识别两种格式的配置文件,分别是yml文件与properties文件,我们可以将application.properties文件换成application.yml,这两个文件都可以被SpringBoot自动识别并加载,但是如果是自定义的配置文件,就最好还是使用properties格式的文件,因为SpringBoot中暂时还并未提供手动加载yml格式文件的功能(这里指注解方式)。
application.properties配置文件欲被SpringBoot自动加载,需要放置到指定的位置:src/main/resource目录下,一般自定义的配置文件也位于此目录之下。
加载的意思就是将文件读取到Spring容器之中,更确切的说就是将各个配置项装载到Spring上下文容器之中供随时取用。
application.properties配置文件是在SpringBoot项目启动的时候被自动加载的,其内部的相关设置会自动覆盖SpringBoot默认的对应设置项,所以的配置项均会保存到Spring容器之中。
以application.yml 为例
项目结构
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-web</artifactId>
- </dependency>
-
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-test</artifactId>
- <scope>test</scope>
- </dependency>
- server:
- port: 8088
-
-
- student:
- name: Jack
- age: 22
- birth: 1990/12/12
-
- package com.example.springbootporperties.conroller;
-
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.ResponseBody;
-
- import java.util.Date;
-
- @Controller
- public class TestController {
- @Value("${student.name}")
- private String name;
- @Value("${student.age}")
- private Integer age;
- @Value("${student.birth}")
- private Date date;
-
- @ResponseBody
- @RequestMapping("/student")
- public String hello() {
- return " name=" +name + " age=" +age +" date=" +date;
- }
- }

赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。