SpringBoot获取properties配置

前言:在项目中,很多时候需要把配置写在properties里,部署的时候也需要切换不同的环境来选择正确的配置的参数,也有时候需要将mq Redis等第三方配置新建一个properties文件在项目中引用。1.因为是spring的环境,当然首先需要搭建好Spring环境。package com.example;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Value;import org.springframework.context.annotation.PropertySource;import org.springframework.core.env.Environment;import org.springframework.stereotype.Component;/** * Created by Administrator on 2016/10/13. */@Componentpublic class ValueTest { public String name = "注入对象的的属性"; @Autowired public Environment env;//当前环境的application.properties的 配置 @Value("注入普通字符串")//注入普通字符串 public String test1; @Value("#{systemProperties['os.name']}")//系统属性配置 public String test2; @Value("#{ T(java.lang.String).valueOf(111)}")//执行某个类的方法 public String test3; @Value("#{valueTest.name}")//某个类的公有属性 public String test4; @Value("${name}")//读取配置在PropertySourcesPlaceholderConfigurer Bean里的properties文件的值 public String test5;}需要注意的是通过 Environment 对象只能获取 Springboot的propertie文件的参数,比如 application-dev.properties。如果是不是application开头的的配置文件,需要单独指定properties的路径@PropertySource("classpath:config.properties")//引用其他单独的properties如果前置一样可以统一配置@ConfigurationProperties(prefix = "spring.wnagnian",locations = "classpath:config/xxx.properties") 2.如果直接用 @Value("${name}") 来取配置的值需要配置 PropertySourcesPlaceholderConfigurer 用来引入properties文件package com.example.config;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;import org.springframework.core.io.ClassPathResource;/** * Created by Administrator on 2016/10/13. */@Configurationpublic class PropertiesConfig { @Bean public PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer() { ClassPathResource resource = new ClassPathResource("config.properties"); PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer(); propertyPlaceholderConfigurer.setLocation(resource); return propertyPlaceholderConfigurer; }}如果是Spring xml配置 classpath:config.properties 取值@Value("#{configProperties['name']}")private String name;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值