0

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.

1 Answer 1

1

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"));
  }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you, the Environment approach solved everything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.