我想在 SomeIfaceDaoImpl 中使用“someotherproperty”值
但是当我调试时,在我的 bean 定义和 bean 构造函数中它始终为 null。我还尝试在我的类中使用 @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
}
}
谢谢。
最佳答案
如果属性文件中没有错误配置,您应该能够直接在 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"));
}
}
关于java - 如何在 Spring 中使用基于注释的属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27167796/