运行时注入(注入外部的值)-属性占位符

本文介绍如何在Spring中使用属性占位符从properties文件中读取配置信息。具体包括使用@PropertySource注解加载配置文件,通过Environment接口访问配置项,以及采用@Value注解注入属性值。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

spring如何获取properties配置文件里的属性?

1、属性占位符

2、SpEL表达式

本章讲解第一种方式:属性占位符。

一、在spring中,处理外部值的最简单方式就是声明属性源并通过Spring的Environment来检索属性。例如:

@Configuration
@PropertySource("classpath:/cn/bobyco/spring/app.properties")
public class ExpressiveConfig {
	@Autowired
	Environment env;
	
	@Bean
	public CompactDisk sgtPeppers() {
		return new SgtPeppers(env.getProperty("disc.title"), env.getProperty("disc.artist"));
	}
}

首先使用@PropertySource注解获取properties源文件。也可以使用@PropertySource(value= {"classpath:/cn/bobyco/spring/app.properties",...})来绑定多个properties源文件。

其次自动装配Environment对象,会将properties文件中的键值对注入到env对象中,通过getProperty来获取key对应的值。注入情况如下图:

二、使用占位符(${...})将值插入到spring bean中。

1、如果依赖组件扫描和自动装配来创建和初始化组件,我们可以使用@Value注解来达到目的。

1)、在成员变量上使用@Value注解

@Component // 声明spring组件
public class Black implements CompactDisk {

	@Value("${disc.title}") // 使用@Value注解来获取源文件中disc.title对应的值
	private String title;
	
	@Value("${disc.artist}")
	private String artist;

	public Black() {
		super();
		// TODO Auto-generated constructor stub
	}



	public String getTitle() {
		return title;
	}



	public void setTitle(String title) {
		this.title = title;
	}



	public String getArtist() {
		return artist;
	}



	public void setArtist(String artist) {
		this.artist = artist;
	}



	@Override
	public void play() {
		// TODO Auto-generated method stub
		System.out.println(this.title + " played by " + this.artist);
	}

}
2)、在构造方法上使用@Value注解
@Component
public class Black implements CompactDisk {

	private String title;
	
	private String artist;

	// 注意,在此种方式时不要有无参构造方法
	public Black(@Value("${disc.title}") String title, @Value("${disc.artist}") String artist) {
		this.artist = artist;
		this.title = title
	}

	

	public String getTitle() {
		return title;
	}



	public void setTitle(String title) {
		this.title = title;
	}



	public String getArtist() {
		return artist;
	}



	public void setArtist(String artist) {
		this.artist = artist;
	}



	@Override
	public void play() {
		// TODO Auto-generated method stub
		System.out.println(this.title + " played by " + this.artist);
	}

}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值