Spring@Value注解,无法获得配置文件中的值

1、我在总的配置类中,配置了两个Bean,用于获取配置文件:

@Configuration
@ComponentScan(basePackages = { "com.szw.SpringExample" }, excludeFilters = {
        @ComponentScan.Filter(type = FilterType.ANNOTATION, value = { Controller.class }),
        @ComponentScan.Filter(type = FilterType.REGEX, pattern = { "com.szw.SpringExample.config.web.*",
                "com.szw.SpringExample.controller.*" })
        })
@Import({ DataConfig.class, AuthConfig.class })
public class RootConfig {
    
    @Bean
    public static PropertiesFactoryBean configProperties() {
        PropertiesFactoryBean config = new PropertiesFactoryBean();
        config.setLocations(new ClassPathResource("/config.properties"));
        return config;
    }

    @Bean
    public static PreferencesPlaceholderConfigurer propertyConfigurer() {
        PreferencesPlaceholderConfigurer configurer = new PreferencesPlaceholderConfigurer();
        try {
            configurer.setProperties(configProperties().getObject());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return configurer;
    }
}

2、配置文件放在src/main/resources下:

clipboard.png

配置文件内容:
db.driverClassName=com.mysql.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/example?useSSL=false
db.userName=root
db.password=123456
db.validationQuery=select 1

3、然后在数据库配置类中获取配置文件中的值:

@Configuration
@EnableTransactionManagement
public class DataConfig {
    
    // 注入数据库连接信息
    @Value("#{configProperties['db.driverClassName']}")
    private String driverClassName;
    @Value("#{configProperties['db.url']}")
    private String url;
    @Value("#{configProperties['db.userName']}")
    private String userName;
    @Value("#{configProperties['db.password']}")
    private String password;
    @Value("#{configProperties['db.validationQuery']}")
    private String validationQuery;
    
    /**
     * DBCP数据库连接池配置
     * @return
     */
    @Bean(destroyMethod = "close")
    public DataSource dataSource() {
        BasicDataSource dataSource = new BasicDataSource();

        dataSource.setDriverClassName(driverClassName);
        dataSource.setUrl(url);
        dataSource.setUsername(userName);
        dataSource.setPassword(password);

        System.out.println("driverClassName:" + driverClassName+"-------url:" + url + "--------username:" + userName + "-----password:"+password);

        dataSource.setInitialSize(2);
        dataSource.setMaxTotal(10000);
        dataSource.setMaxIdle(5);
        dataSource.setMinIdle(2);
        dataSource.setMaxWaitMillis(600000);
        dataSource.setTestOnBorrow(false);
        dataSource.setTestWhileIdle(true);
        dataSource.setValidationQuery(validationQuery);

        return dataSource;
    }

可是却获取不到值,并且控制台有一个警告:

{---}2017-07-07 14:25:55,193 [localhost-startStop-1] WARN [org.springframework.context.annotation.ConfigurationClassPostProcessor] - Cannot enhance @Configuration bean definition 'dataConfig' since its singleton instance has been created too early. The typical cause is a non-static @Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.

但是我获取配置文件的bean已经是static的了

阅读 19.3k
4 个回答

···java

@Bean
public static PropertySourcesPlaceholderConfigurer placeholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
}
只添加一个这个bean, 然后用注解@PropertySource("path"),

在要注入的地方 @Value("${db.userName}"), 不用configProperties['db.userName']}这种方式、

改成 application.properties

根据错误信息看,应该是静态方法的错

新手上路,请多包涵

@Value 不可以在@Configuration 配置类中使用 加载顺序决定 只能在@service @control 等等bean中使用

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题