spring使用注解方式读取properties文件时读取不到对应的值
·
问题现象:
使用注解方式读取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,即放开上述代码的注释部分即可,如下:

放开注释后执行结果如下:

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)