spring使用注解方式读取properties文件时读取不到对应的值

本文介绍在Spring框架中使用注解方式读取properties文件的方法,包括@PropertySource和@Value的使用,以及如何解决读取不到属性值的问题。

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

问题现象:

使用注解方式读取properties文件时,发现读取不到属性值:代码如下

import java.beans.PropertyVetoException;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.PropertyResourceConfigurer;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;

import com.mchange.v2.c3p0.ComboPooledDataSource;

@Configuration
@PropertySource("classpath:db.properties")
public class SpringConfiguration {
//	@Bean
//	public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
//		return new PropertySourcesPlaceholderConfigurer();
//	}
	
	@Value("${jdbc.driverClass}")
	public String driverClass;

	@Value("${jdbc.jdbcUrl}")
	public String jdbcUrl;

	@Value("${jdbc.user}")
	public String user;

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

	/**
	 * dataSource:C3P0数据源. <br>
	 * 
	 * @author liuyun
	 * @return
	 * @throws PropertyVetoException
	 * @since 2019年9月1日下午3:37:53
	 */
	@Bean(name = "dataSource")
	public ComboPooledDataSource dataSource() throws PropertyVetoException {
		ComboPooledDataSource dataSource = new ComboPooledDataSource();
		dataSource.setDriverClass(driverClass);
		dataSource.setJdbcUrl(jdbcUrl);
		dataSource.setUser(user);
		dataSource.setPassword(password);
		System.out.println("driverClass=" + driverClass + ", jdbcUrl=" + jdbcUrl + ", user=" + user + ", password="
				+ password + "]");
		return dataSource;
	}
	
	public static void main(String[] args) {
		AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext();
		ctx.register(SpringConfiguration.class);
		ctx.refresh();
		// 判断是否存在PropertyResourceConfigurer的实现类
		PropertyResourceConfigurer bean = ctx.getBean(PropertyResourceConfigurer.class);
		System.out.println("PropertyResourceConfigurer="+bean);
		ctx.close();
	}

运行结果:

在这里插入图片描述
可以看出:为获取所需的配置,且PropertyResourceConfigurer的实现类在容器中也没有找到

解决方法:

在容器中加入所需的bean,即放开上述代码的注释部分即可,如下:
在这里插入图片描述
放开注释后执行结果如下:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值