springboot加载指定的属性文件(properties和yml文件)

转自:springboot加载指定的属性文件(properties和yml文件),更优阅读体验:http://www.kongzid.com/

目录

1、properties配置文件

1.1 默认名称的配置文件application.properties

1.1.1 @Value注解注入属性到bean

1.1.2 @ConfigurationProperties注解注入属性到bean

1.1.3 @Value与@ConfigurationProperties结合使用

1.2 非默认名称的配置文件config/mail.properties

1.2.1、@PropertySource注解加载properties文件

1.2.2、@PropertySource注解加载yml文件

2、yml配置文件支持

2.1 yml配置文件 config/mail.yml

2.2 解析yml文件的工厂类

2.3 @PropertySource注解加载yml文件

3、@value注解其他形式


springboot提供了多个注解可以将外部的值动态注入到Bean中,最常用的包括@Value注解,@ConfigurationProperties注解。这些注解只能读取默认的配置文件application.properties,要想加载非默认配置文件,需结合@PropertySource使用。

1、properties配置文件

1.1 默认名称的配置文件application.properties

spring.jdbc.username=admin
spring.jdbc.password=pwd123
...

1.1.1 @Value注解注入属性到bean

@Component
public class JdbcConfig
{
    @Value("${spring.jdbc.username}")
    private String username;

    @Value("${spring.jdbc.password}")
    private String password;

    //省略getter与setter方法...
}

1.1.2 @ConfigurationProperties注解注入属性到bean

@Component
@ConfigurationProperties(prefix = "spring.jdbc")
public class JdbcConfig
{
    private String username;
 
    private String password;
 
    //省略getter与setter方法...
}

1.1.3 @Value与@ConfigurationProperties结合使用

假如在配置文件中还有一个spring.name属性,则可以按如下形式使用。

@Component
@ConfigurationProperties(prefix = "spring.jdbc")
public class JdbcConfig
{
    private String username;
 
    private String password;

    @Value("${spring.name}")
    private String name;
 
    //省略getter与setter方法...
}

1.2 非默认名称的配置文件config/mail.properties

mail.host=smtp.qq.com
mail.port=587
...

1.2.1、@PropertySource注解加载properties文件

PropertySource注解的作用是加载指定的属性文件,配置属性如下@PropertySource(value= {"classpath:config/mail.properties"},ignoreResourceNotFound=false,encoding="UTF-8",name="mail.properties"),其中value是设置需要加载的属性文件,可以一次性加载多个(多个时以,分隔); encoding用于指定读取属性文件所使用的编码,我们通常使用的是UTF-8;ignoreResourceNotFound含义是当指定的配置文件不存在是否报错,默认是false;如这里配置的config/mail.properties,若在classpath路径下不存在时,则ignoreResourceNotFound为true的时候,程序不会报错,如果ignoreResourceNotFound为false的时候,程序直接报错。实际项目开发中,最好设置ignoreResourceNotFound为false,该参数默认值为false。name的值我们设置的是mail.properties。这个值在Springboot的环境中必须是唯一的,如果不设置,则值为:“class path resource [config/mail.properties]“。

@Component
@ConfigurationProperties(prefix = "mail")
@PropertySource(value = "classpath:config/mail.properties",encoding = "UTF-8")
public class MailConfig
{
    private String host;
 
    private String port;
 
    //省略getter与setter方法...
}

1.2.2、@PropertySource注解加载yml文件

在1.2.1中,若配置文件为config/mail.yml时,配置属性不会注入到MailConfig的bean中。查看源代码发现,@PropertySource不支持 yml 文件的解析,该注解有个factory 这个属性,作为解析资源文件的工厂类,默认实现是 DefaultPropertySourceFactory,只需要实现能解析yml的工厂类即可以解决该问题。

2、yml配置文件支持

2.1 yml配置文件 config/mail.yml

mail:
  host: smtp.qq.com
  port: 587

2.2 解析yml文件的工厂类

import org.springframework.beans.factory.config.YamlPropertiesFactoryBean;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.core.env.PropertySource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertySourceFactory;

import java.io.IOException;
import java.util.Properties;

/**
 * PropertySource支持yml配置文件
 *
 * @Author kongzi
 * @Version 1.0
 */
public class YamlPropertySourceFactory implements PropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        YamlPropertiesFactoryBean factory = new YamlPropertiesFactoryBean();
        factory.setResources(resource.getResource());
        factory.afterPropertiesSet();
        Properties ymlProperties = factory.getObject();
        String propertyName = name != null ? name : resource.getResource().getFilename();
        return new PropertiesPropertySource(propertyName, ymlProperties);
    }
}

2.3 @PropertySource注解加载yml文件

@Component
@ConfigurationProperties(prefix = "mail")
@PropertySource(value = "classpath:config/mail.yml", factory = YamlPropertySourceFactory.class)
public class MailConfig
{
    private String host;
 
    private String port;
 
    //省略getter与setter方法...
}

3、@value注解其他形式

@Value注解实现以下几种情况:
(1)注入普通字符;
(2)注入操作系统属性;
(3)注入表达式运算结果;
(4)注入其他Bean的属性;
(5)注入文件内容;
(6)注入网址内容;
(7)注入属性文件。

package com.kongzi;
 
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.env.Environment;
import org.springframework.core.io.Resource;
 
/**
 * 配置类
 **/
@Configuration
@ComponentScan("com.kongzi")
@PropertySource("classpath:db.properties")
public class ElConfig
{
    /**
     * 注入普通字符串
     */
    @Value("您好,欢迎访问 carefree 的博客")
    private String comment;
 
    /**
     * 注入操作系统属性
     */
    @Value("#{systemProperties['os.name']}")
    private String osName;
 
    /**
     * 注入表达式运算结果
     */
    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber;
 
    /**
     * 注入其他Bean的属性
     */
    @Value("#{otherUser.userName}")
    private String fromUserName;
 
    @Value("#{otherUser.blogUrl}")
    private String fromBlogUrl;
 
    /**
     * 注入文件资源
     */
    @Value("classpath:info.txt")
    private Resource testFile;
 
    /**
     * 注入网址资源
     */
    @Value("https://blog.csdn.net/carefree31441")
    private Resource testUrl;
 
    /**
     * 注入配置文件
     */
    @Value("${jdbc.driver}")
    private String jdbc_driver;
 
    @Value("${jdbc.url}")
    private String jdbc_url;
 
    @Value("${jdbc.username}")
    private String jdbc_username;
 
    @Value("${jdbc.password}")
    private String jdbc_password;
 
    @Autowired
    private Environment environment;
 
    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfigurer()
    {
        return new PropertySourcesPlaceholderConfigurer();
    }
 
    public void outputResource()
    {
        try
        {
            System.out.println("注入普通字符串:");
            System.out.println(comment);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入操作系统属性:");
            System.out.println(osName);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入表达式运算结果:");
            System.out.println(randomNumber);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入其他Bean的属性:");
            System.out.println("用户名称:" + fromUserName);
            System.out.println("博客地址:"+ fromBlogUrl);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入文件资源:");
            System.out.println("文件中的内容:" + IOUtils.toString(testFile.getInputStream()));
            System.out.println("------------------------------------------------");
 
            System.out.println("注入配置文件(方式一):");
            System.out.println("数据库驱动:" + jdbc_driver);
            System.out.println("数据库连接:" + jdbc_url);
            System.out.println("数据库用户:" + jdbc_username);
            System.out.println("数据库密码:" + jdbc_password);
            System.out.println("------------------------------------------------");
 
            System.out.println("注入配置文件(方式二):");
            System.out.println("数据库驱动:" + environment.getProperty("jdbc.driver"));
            System.out.println("数据库连接:" + environment.getProperty("jdbc.url"));
            System.out.println("数据库用户:" + environment.getProperty("jdbc.username"));
            System.out.println("数据库密码:" + environment.getProperty("jdbc.password"));
            System.out.println("------------------------------------------------");
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
}

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

孔子-说

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值