【问题标题】:PropertyPlaceholderConfigurer accessing property file using @PropertySource errorPropertyPlaceholderConfigurer 使用 @PropertySource 错误访问属性文件
【发布时间】:2015-07-18 02:16:36
【问题描述】:

我正在尝试通过 @PropertySource 注释将数据源变量注入我的 PropertyPlaceholderConfigurer,但出现错误“无法解析字符串值“${jdbc.url}”中的占位符 'jdbc.url'

我的配置类

@Configuration
@ComponentScan(basePackages="com.spring.contacts")
@EnableWebMvc
@PropertySource(value = "file:${catalina.base}/spring.properties")
public class MvcConfiguration extends WebMvcConfigurerAdapter{


@Bean
public static PropertyPlaceholderConfigurer properties(){
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
return ppc;
}

@Value( "${jdbc.url}" ) 
private String jdbcUrl;
@Value( "${jdbc.driverClassName}" ) 
private String driverClassName;
@Value( "${jdbc.username}" ) 
private String username;
@Value( "${jdbc.password}" ) 
private String password;

@Bean
public ViewResolver getViewResolver(){
    InternalResourceViewResolver resolver = new   InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/JDBC/");
    resolver.setSuffix(".jsp");
    return resolver;
}

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
}


@Bean(name="datasource")
public DataSource getDataSource() {
    DriverManagerDataSource ds = new DriverManagerDataSource();
ds.setDriverClassName(driverClassName);
ds.setUrl(jdbcUrl);
ds.setUsername(username);
ds.setPassword(password);
return ds;
}

spring.properties

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root

我从eclipse启动tomcat -Dcatalina.base="C:\apache-tomcat-8.0.21"

追踪

Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private java.lang.String com.spring.contacts.config.MvcConfiguration.jdbcUrl; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'jdbc.url' in string value "${jdbc.url}"
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 31 more

【问题讨论】:

    标签: spring-mvc spring-boot


    【解决方案1】:

    我通过使用解决了它 PropertySourcesPlaceholderConfigurer 而不是 PropertyPlaceholderConfigurer

    【讨论】:

      猜你喜欢
      • 2013-06-30
      • 2013-08-21
      • 1970-01-01
      • 2018-02-15
      • 2012-03-24
      • 1970-01-01
      • 1970-01-01
      • 2014-07-21
      • 1970-01-01
      相关资源
      最近更新 更多