Spring——PropertySource详解

在Spring中,PropertySource通常用来加载外部配置文件中的属性,比如application.properties或者其他自定义的属性文件。PropertySource可以被Environment对象加载,并通过Environment来获取属性值。

Spring提供了多种实现PropertySource的方式,包括:

  • ResourcePropertySource:从资源文件中加载属性。
  • MapPropertySource:基于Map的属性源。
  • SystemEnvironmentPropertySource:从系统环境变量中加载属性。
  • SystemPropertiesPropertySource:从系统属性中加载属性。

代码如下:

首先,在application.properties配置文件中定义一些属性:

app.name=MyApp
app.version=1.0

然后,在Spring配置类中加载PropertySource:

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.core.io.ClassPathResource;

@Configuration
public class AppConfig {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
        PropertySourcesPlaceholderConfigurer configurer = new PropertySourcesPlaceholderConfigurer();
        configurer.setLocation(new ClassPathResource("application.properties"));
        return configurer;
    }
}

接下来,在应用程序中使用@Value注解来注入属性值:

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class MyBean {

    @Value("${app.name}")
    private String appName;

    @Value("${app.version}")
    private String appVersion;

    public void displayProperties() {
        System.out.println("App Name: " + appName);
        System.out.println("App Version: " + appVersion);
    }
}

通过PropertySourcesPlaceholderConfigurer类加载了application.properties文件作为PropertySource,然后通过@Value注解将属性值注入到MyBean类中。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值