问题现象:
使用注解方式读取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,即放开上述代码的注释部分即可,如下:
放开注释后执行结果如下: