我试图通过@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
答案 0 :(得分:0)
我用它来解决它
PropertySourcesPlaceholderConfigurer
代替PropertyPlaceholderConfigurer