• SpringBoot自定义文件配置


    为了让 SpringBoot 更好的生成配置元数据文件,我们需要添加如下依赖,该依赖只会在编译时调用,所以不用担心会对生产造成影响

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-configuration-processor</artifactId>
        <optional>true</optional>
    </dependency>

    1. 定义一个名为 myApp.properties 的资源文件,自定义配置文件的命名不强制 application 开头

    com.ma.name=hello
    com.ma.title=shen fu shi

    2. 定义ConfigBean2文件,用来映射我们在 myApp.properties 中的内容

    @Component
    @PropertySource("classpath:myApp.properties")
    @ConfigurationProperties(prefix="com.ma")
    public class ConfigBean2 {
        private String name;
        private String title;
    
        public String getName() {
            return name;
        }
    
        public String getTitle() {
            return title;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public void setTitle(String title) {
            this.title = title;
        }
    }

    3. 在 UserController用来注入 ConfigBean2测试我们编写的代码

    @RestController
    @RequestMapping("properties")
    public class UserController {
    
        private static final Logger log = LoggerFactory.getLogger(UserController.class);
        private final ConfigBean config;
        private final ConfigBean2 config2;
        @Autowired
        public UserController(ConfigBean config,ConfigBean2 config2){
            this.config=config;
            this.config2=config2;
        }
    
        @GetMapping("/1")
        public String hello(){
            log.info("=============》隆庆来了");
            return config.getName()+config.getTitle();
        }
    
        @GetMapping("/2")
        public String hello2(){
            log.info("=============》宁缺来了");
            return config2.getName()+config2.getTitle();
        }
    }

    4. 打开浏览器,输入如下地址: http://localhost:8080/properties/2,观察控制台和界面,监听到如下内容则表示程序正确

    总结

    • 掌握@ConfigurationProperties@PropertySource 注解的用法及作用
    • 掌握编写自定义配置
  • 相关阅读:
    Android消息机制解析
    ViewGroup事件分发机制解析
    Android Ptrace Inject
    Android GOT Hook
    Android Exception Hook
    Android Inline Hook
    esp8266 SDK开发之编译流程
    XML文件解析数据结构
    esp8266 SDK开发之GPIO中断
    esp8266 SDK开发之环境搭建
  • 原文地址:https://www.cnblogs.com/yangjiming/p/10033184.html
Copyright © 2020-2023  润新知