SpringBoot获取properties配置

时间:2022-06-26
本文章向大家介绍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.
 */
@Component
public 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}")//Springboot的properties,或者配置在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.
 */
@Configuration
public class PropertiesConfig {

    @Bean
    public PropertySourcesPlaceholderConfigurer createPropertySourcesPlaceholderConfigurer() {
        ClassPathResource resource = new ClassPathResource("config.properties");
        PropertySourcesPlaceholderConfigurer propertyPlaceholderConfigurer = new PropertySourcesPlaceholderConfigurer();
        propertyPlaceholderConfigurer.setLocation(resource);
        return propertyPlaceholderConfigurer;
    }
}

如果是Spring xml配置

   <bean id="configProperties" class="org.springframework.beans.factory.config.PropertiesFactoryBean">  
       <property name="locations">  
           <list>  
               <value>classpath:config.properties</value>  
           </list>  
       </property>  
    </bean>  
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PreferencesPlaceholderConfigurer">  
        <property name="properties" ref="configProperties" />  
    </bean>  

取值

@Value("#{configProperties['name']}")
private String name