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();
        }
    }

    结果:

    项目结构:

     

  • 相关阅读:
    点击空白处隐藏盒子
    java缓存技术
    使用Java处理大文件
    java实现把一个大文件切割成N个固定大小的文件
    笔记:Java的IO性能调整
    NIO之轻松读取大文件
    java读写文件,读超大文件
    java读取大文件 超大文件的几种方法
    java web服务器cpu占用过高的处理
    软件开发各类文档模板
  • 原文地址:https://www.cnblogs.com/hbolin/p/10659871.html
Copyright © 2011-2022 走看看