简体   繁体   中英

How to work with annotation based properties in Spring

I would like to use 'someotherproperty' value inside SomeIfaceDaoImpl

But when I debug, it's always null, inside my bean definition and inside my bean constructor as well. I also tried to use @Value annotation inside my class but this does not work either.

However, all database values works fine and available inside jdbcTemplate bean.

My properties file contains

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

My configuration class:

@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
    }

}

Thank you.

You should be able to use 'someotherproperty' directly in your bean method is there's no misconfiguration in your property file. A better approach to avoid having multiple fields annotated with @Value would be using the Environment abstraction

@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"));
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM