【问题标题】:How to work with annotation based properties in Spring如何在 Spring 中使用基于注解的属性
【发布时间】:2014-11-27 10:02:07
【问题描述】:

我想在 SomeIfaceDaoImpl 中使用 'someotherproperty' 值

但是当我调试时,它总是空的,在我的 bean 定义和我的 bean 构造函数中也是如此。我也尝试在我的类中使用 @Value 注释,但这也不起作用。

但是,所有数据库值都可以正常工作,并且可以在 jdbcTemplate bean 中使用。

我的属性文件包含

database.url=jdbc:mysql://localhost:3306/databasename
database.username=root
database.password=password
someotherproperty=HelloWorld

我的配置类:

@Configuration
@Profile("production")
@ComponentScan(basePackages = { "com.packagename" })
@PropertySource({"classpath:packagename.properties"})
public class ContextConfig {
    @Value("${database.url}")
    private String url;
    @Value("${database.username}")
    private String username;
    @Value("${database.password}")
    private String password;


    @Value("${someotherproperty}")
    private String someotherproperty;

    @Bean(name = "jdbcTemplate")
    public JdbcTemplate jdbcTemplate() {
        JdbcTemplate jdbcTemplate = new JdbcTemplate();
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setUrl(StringUtil.appendObjects(url, "?",     "useServerPrepStmts=false&rewriteBatchedStatements=true"));
        dataSource.setDriverClassName("com.mysql.jdbc.Driver");
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        jdbcTemplate.setDataSource(dataSource);
        return jdbcTemplate;
    }

    @Bean
    public ISomeIfaceDao iSomeIfaceDao() {
        return new ISomeIfaceDaoImpl(); //<---- I would like to have someotherproperty value here or inside the constructor
    }

}

谢谢。

【问题讨论】:

    标签: java spring annotations


    【解决方案1】:

    如果您的属性文件中没有错误配置,您应该可以直接在您的 bean 方法中使用“someotherproperty”。避免使用@Value 注释的多个字段的更好方法是使用Environment 抽象

    @Configuration
    @Profile("production")
    @ComponentScan(basePackages = { "com.packagename" })
    @PropertySource({"classpath:packagename.properties"})
    public class ContextConfig {
    
      @Autowired
      private Environment env;
    
      @Bean
      public ISomeIfaceDao iSomeIfaceDao() {
        return new ISomeIfaceDaoImpl(env.getRequiredProperty("someotherproperty"));
      }
    }
    

    【讨论】:

    • 谢谢,环境方法解决了一切。
    猜你喜欢
    • 2013-07-29
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 1970-01-01
    • 1970-01-01
    • 2011-09-19
    • 2012-08-06
    • 2015-04-09
    相关资源
    最近更新 更多