zoukankan      html  css  js  c++  java
  • Spring Boot 3.自定义配置

    自定义配置需要导入以下配置

            <!--自定义配置-->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-configuration-processor</artifactId>
                <optional>true</optional>
            </dependency>

    配置属性,有多种方式:

    第一种是在application.properties中配置,但如果是我们额外的自定义配置的话,是不推荐使用这种方式,在application.properties中一般都是配置Spring Boot的配置

    custominapp.name="在application.properties中读取属性值"

    编写读取的Bean:prefix 是读取的前缀

    package com.example.springbootstudy;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.stereotype.Component;
    
    @ConfigurationProperties(prefix = "custominapp")
    @Component
    public class CustomInApp {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    第二种方式:

    新建cutompro.properties文件

    custominpro.name="在custompro.properties读取属性值"

    编写读取的Bean:@PropertySource("classpath:/cutompro.properties") 用于指明读取的路径,记住有个 / 斜杆

    package com.example.springbootstudy;
    
    import org.springframework.boot.context.properties.ConfigurationProperties;
    import org.springframework.context.annotation.PropertySource;
    import org.springframework.stereotype.Component;
    
    @ConfigurationProperties(prefix = "custominpro")
    @Component
    @PropertySource("classpath:/cutompro.properties")
    public class CustomInPro {
        private String name;
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    }

    测试:

    package com.example.springbootstudy;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.GetMapping;
    import org.springframework.web.bind.annotation.RestController;
    
    @RestController
    public class HelloWorldController {
    
        @Autowired
        CustomInApp customInApp;
    
        @Autowired
        CustomInPro customInPro;
    
        @GetMapping("custom")
        public String customproperties() {
            return "自定义属性:" + customInApp.getName() + "---" + customInPro.getName();
        }
    }

    结果:

    项目结构:

     

  • 相关阅读:
    zookeeper-3.4.6集群安装
    js 函数参数个数
    警告: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:webProject'
    开始写博客了
    使用wsimport对接WebService 生成Java客户端
    LocalDateTime反序列化报错:cannot deserialize from Object value
    MinIO上传文件The difference between the request time and the server's time is too large.异常
    Maven scope属性说明
    SpringBoot整合MinIO实现文件上传 附demo
    Map从入门到性能分析-imooc学习笔记【完】
  • 原文地址:https://www.cnblogs.com/hbolin/p/10659871.html
Copyright © 2011-2022 走看看