1

如何在使用 Spring 3.2 MVC 应用程序的基于 java 的配置时读取属性文件的值?我的配置类扩展了 WebMvcConfigurationAdapter...

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = "com.foo.bara" , excludeFilters = { @Filter( Configuration.class ) } )
@PropertySource( {"classpath:abc.properties", "classpath:persistence.properties" } )
public class MokaWebAppContext extends WebMvcConfigurerAdapter { 
    @Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
    PropertySourcesPlaceholderConfigurer pspc = new PropertySourcesPlaceholderConfigurer();
    Resource[] resources = new ClassPathResource[ ] {
            new ClassPathResource( "persistence.properties" ),
            new ClassPathResource( "abc.properties" )
    };
    pspc.setLocations( resources );
    pspc.setIgnoreUnresolvablePlaceholders( true );
    return pspc;
  }
    ...
}

尝试访问此资源时

@Value('${persistence.db.driverClass}') private String driverClassName;

${persistence.db.driverClass} 无法识别。

从@Configuration 类的属性文件中读取值我需要做什么?我想我不能在这个地方使用环境实例,可以吗?

4

1 回答 1

3

以正确的方式做...并且有效!当然,您必须使用双引号而不是单引号:

@Value("${persistence.db.driverClass}") private String driverClassName;

而不是

@Value('${persistence.db.driverClass}') private String driverClassName;
于 2013-10-01T09:12:07.430 回答