美文网首页Spring Boot
springboot-配置文件

springboot-配置文件

作者: inke | 来源:发表于2017-07-07 18:36 被阅读258次

配置文件

启动类:

SpringbootStudyApplication.java 名字随便定,@SpringBootApplication决定启动类

@SpringBootApplication
public class SpringbootStudyApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootStudyApplication.class, args);
    }
}

配置文件:

格式一:

application.properties

例如:添加全局访问路径和修改 Tomcat 的端口号

server.context-path=/demo
server.port=8081

格式二:

  • 系统属性 application.yml

    例如:添加全局访问路径context-path 和 修改 Tomcat 的端口号

    server:
      port: 8000
      # 解决乱码问题
      tomcat:
        uri-encoding: utf-8
      # 配置全局访问根路径,Spring boot默认是/ ,这样直接通过http://ip:port/就可以访问到index页面
      context-path: /test
    
  • 自定义属性:application.yml

    age: 18 # 自定义属性
    name: inke # 自定义属性
    content: "name:${name},age:${age}" #配置引用配置
    

    在代码中引用 HelloController.java

    @Value("${age}")
    private Integer age;//@value可以获取application.yml配置的值
    
    @RestController
    public class HelloController {
    }    
    
  • 类和属性关联

    application.yml

    person:
      age: 18 # 自定义属性
      name: inke # 自定义属性
    

    Person.java

    @Component
    @ConfigurationProperties(prefix = "person")
    public class Person {
        private String name;
        private Integer age;
    
        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;
        }
    }
    

    在代码中引用 HelloController.java

    @RestController
    public class HelloController {
    
    //    @Value("${age}")
    //    private Integer age;
    //
    //    @Value("${content}")
    //    private String content;
    
        @Autowired
        private Person person;
    
        @RequestMapping(value = "/hello")
        public String sayHello() {
            return "hello world name:" + person.getName() + " , age:" + person.getAge();
        }
    }
    

多个配置文件切换

application.yml 通过 active 指定的属性的环境:dev 还是 prod

spring:
  profiles:
    active: prod

application-dev.yml

person:
  age: 18 # 自定义属性
  name: dev001 # 自定义属性

application-prod.yml

person:
  age: 18 # 自定义属性
  name: prod001 # 自定义属性

启动的时候,会根据 active 指定的环境属性文件进行加载。

相关文章

网友评论

    本文标题:springboot-配置文件

    本文链接:https://www.haomeiwen.com/subject/mvjrhxtx.html