热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

SpringBoot属性注入ConfigurationProperties

SpringBoot属性注入ConfigurationProperties,Go语言社区,Golang程序员人脉社

问题:ConfigurationProperties如何进行对象的赋值,
例, JdbcProperties中有 View对象,如何初始化View中的 prefix,suffix

ConfigurationProperties 的 Relaxed binding:松散绑定
不严格要求属性文件中的属性名与成员变量名一致。支持驼峰,中划线,下划线等等转换,甚至支持对象引导。比如:user.friend.name:代表的是user对象中的friend属性中的name属性,显然friend也是对象。

@ConfigurationProperties(prefix = "jdbc")
public class JdbcProperties {

    private String driverClassName;
    private String url;
    private String username;
    private String password;

    //配置文件以 jdbc.view 开头
    private final View view = new View();

    public String getDriverClassName() {
        return driverClassName;
    }

    public void setDriverClassName(String driverClassName) {
        this.driverClassName = driverClassName;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public  View getView(){
        return this.view;
    }


    public static class View {

        /**
         * Spring MVC view prefix.
         */
        private String prefix;

        /**
         * Spring MVC view suffix.
         */
        private String suffix;

        public String getPrefix() {
            return this.prefix;
        }

        public void setPrefix(String prefix) {
            this.prefix = prefix;
        }

        public String getSuffix() {
            return this.suffix;
        }

        public void setSuffix(String suffix) {
            this.suffix = suffix;
        }

    }
}

application.properties
如果想要初始化View中的 prefix和suffix,则前缀应该为 jdbc.view

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mytest?characterEncoding=utf-8
jdbc.username=ldmiao
jdbc.password=ldm1991

jdbc.view.prefix = qianzhui
jdbc.view.suffix = houzhui

测试:
在Controller中 使用@EnableConfigurationProperties(JdbcProperties.class)引入配置类
通过构造方法注入 JdbcProperties

@RequestMapping("springboot")
@Controller
@EnableConfigurationProperties(JdbcProperties.class)
public class HelloController {

    public HelloController(JdbcProperties jdbcProperties){
        System.out.println(jdbcProperties.getView().getPrefix());
    }

    @Autowired
    private DataSource dataSource;
   @GetMapping("show")
    public String test(){
        return "hello";
    }
}

debug启动,启动服务的时候就会执行构造方法


推荐阅读
author-avatar
榴莲味蛋筒
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有