zoukankan      html  css  js  c++  java
  • Spring Boot 中读取配置属性

    1.@Value

    数组属性在配置文件中用逗号隔开,需要注意的一点:在spring框架中controller层获取属性需要在spring和springmvc的配置文件中都添加属性文件引用,不然启动时无法读取属性文件。而在springboot直接配置属性就可在controller层获取。

    2.Environment

    通过注入获取Environment对象,然后再获取定义在配置文件的属性值;或者通过ApplicationContext获取Environment对象后再获取值

    @RestController
    public class ConfigureController extends BaseController{
        private static final String MINE_HELLO="mine.hello";
        private static final String MINE_INT_ARRAY="mine.int-array";
        @Resource
        private Environment env;
        @RequestMapping("config")
        public void config(){
            String a=applicationContext.getEnvironment().getProperty(MINE_HELLO);
            String c=applicationContext.getEnvironment().getProperty(MINE_INT_ARRAY);
            System.out.println(a);
            System.out.println(c);
        }
        @RequestMapping("envir")
        public void envir(){
            String a=env.getProperty(MINE_HELLO);
            String c=env.getProperty(MINE_INT_ARRAY);
            System.out.println(a);
            System.out.println(c);
        }
    }

    这里BaseController中注入了一个ConfigurableApplicationContext对象。获取的属性均为String类型

    3.@ConfigurationProperties

    @ConfigurationProperties作用在类上,用于注入Bean属性,然后再通过当前Bean获取注入值

    @RestController
    
    public class PropertiesController {
        @Autowired
        private Attribute attribute;
        @RequestMapping("property")
        public void property(){
            System.out.println(attribute.getHello());
            System.out.println(Arrays.toString(attribute.getIntArray()));
        }
    }
    @Component
    //@PropertySource("classpath:application.yaml")
    @ConfigurationProperties(prefix = "mine")
    class Attribute{
        private String hello;
        private Integer[] intArray;
    
        public void setHello(String hello) {
            this.hello = hello;
        }
    
        public void setIntArray(Integer[] intArray) {
            this.intArray = intArray;
        }
    
        public String getHello() {
            return hello;
        }
    
        public Integer[] getIntArray() {
            return intArray;
        }
    }

    我的属性名为int-array,在Attribute类中还是可以用驼峰命名法获取属性

    PropertiesLoaderUtils,暂不了解

  • 相关阅读:
    [转载]datatable中只取前7条数据
    [转载]序列化的作用
    [转载]ASP.NET几种清除页面缓存的方法
    Page_Init()和page_load()区别
    [转载]回调函数
    编程规约
    语法知识【Python核心编程】
    Web基础概念扫盲
    【Tomcat源码调试-1】环境搭建(MyEclipse)
    小希的数表题解
  • 原文地址:https://www.cnblogs.com/psxfd4/p/11975718.html
Copyright © 2011-2022 走看看