zoukankan      html  css  js  c++  java
  • SpringBoot属性配置

    SpringBoot属性配置

      创建Spring Boot项目时,会默认生成一个全局配置文件application.properties(可以修改后缀为.yml),在src/main/resources目录下或者类路径的/config下。

      我们可以通过修改该配置文件来对一些默认配置的配置值进行修改。

    一、项目默认属性配置文件

    1.修改tomcat端口号

      spring boot 开发web应用的时候,默认tomcat的启动端口为8080,如果需要修改默认的端口,则需要在application.yml添加以下记录:

    server:
      port: 8888

       重启项目,启动日志可以看到:Tomcat started on port(s): 8888 (http) 启动端口为8888,

      浏览器中访问 http://localhost:8888 能正常访问。

    2.修改访问路径

      spring boot 开发web应用的时候,访问路径为/,如果需要修改访问路径,则需要在application.yml添加以下记录:

    server:
        port: 8888
        servlet:
            context-path: /springboot

       重启项目,启动日志就可以看到:Tomcat started on port(s): 8888 (http) with context path '/springboot',

      浏览器中访问 http://localhost:8888/springboot 能正常访问。

    二、自定义属性及读取

    1.在application.yml定义几个常量:

    offcn_ip:
        1.1.1.1
    offcn_port:
        9999

     

    2.在Controller类中,使用@Value注解,读取自定义属性

    @RestController
    public class HelloConfigController {
        @Value("${offcn_ip}")
        private String offcn_ip;
    
        @Value("${offcn_port}")
        private String offcn_port;
    
        @GetMapping("/getValue")
        public String getValue(){
            return "ip:"+offcn_ip+"------port:"+offcn_port;
        }
    }

      访问http://localhost:8888/springboot/getvalue,出现如图结果:

    三、实体类属性赋值

    1.定义配置文件(.yml)

    userbody:
      name: 张三
      password: 123456
      birthday: 1997.08.22
      mobile: 15530499944
      address: 北京市

    2.创建实体类

      需要在实体类上增加注解@ConfigurationProperties,并指定prrfix前缀。

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    @ConfigurationProperties(prefix = "userbody")
    public class UserBody {
        private String name;
        private String password;
        private String birthday;
        private String mobile;
        private String address;
    
    }

     

    3.编写controller类。

    @RestController
    @EnableConfigurationProperties({UserBody.class})  //@EnableConfigurationProperties注解需要加在调用类上,或者加在启动类上也可以。
    public class UserBodyController {
        @Autowired
        UserBody userBody;
    
        @GetMapping("/getUserBody")
        public String getUser(){
            return userBody.toString();
        }
    
    }

    4.在浏览器中访问。http://localhost:8888/springboot/getUserBody

  • 相关阅读:
    Oracle数据库相关问题
    常用Oracle数据库查询SQL
    VS2019添加引用错误:COM组件调用返回错误HRESULT E_FAIL
    C#.NET重点知识点汇总(三)
    C#.NET重点知识点汇总(二)
    C#.NET重点知识点汇总(一)
    ajax的19道经典面试题
    C#设计模式——抽象工厂模式
    C#设计模式——工厂方法模式
    C#设计模式——简单工厂模式
  • 原文地址:https://www.cnblogs.com/gxh494/p/11802533.html
Copyright © 2011-2022 走看看