Java 如何在Spring中使用基于注释的属性
我想在SomeIfacedaImpl中使用'someotherproperty'值 但当我调试时,它总是空的,在我的bean定义和bean构造函数中也是如此。我还尝试在类中使用@Value注释,但这也不起作用 但是,所有数据库值都可以在JDBCTemplatebean中正常工作并可用 我的属性文件包含Java 如何在Spring中使用基于注释的属性,java,spring,annotations,Java,Spring,Annotations,我想在SomeIfacedaImpl中使用'someotherproperty'值 但当我调试时,它总是空的,在我的bean定义和bean构造函数中也是如此。我还尝试在类中使用@Value注释,但这也不起作用 但是,所有数据库值都可以在JDBCTemplatebean中正常工作并可用 我的属性文件包含 database.url=jdbc:mysql://localhost:3306/databasename database.username=root database.password=pas
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
}
}
@配置
@简介(“生产”)
@ComponentScan(basePackages={“com.packagename”})
@PropertySource({“classpath:packagename.properties”})
公共类ContextConfig{
@值(“${database.url}”)
私有字符串url;
@值(“${database.username}”)
私有字符串用户名;
@值(“${database.password}”)
私有字符串密码;
@值(“${someotherproperty}”)
私有字符串或其他属性;
@Bean(name=“jdbcTemplate”)
公共JdbcTemplate JdbcTemplate(){
JdbcTemplate JdbcTemplate=新JdbcTemplate();
BasicDataSource数据源=新的BasicDataSource();
setUrl(StringUtil.appendObjects(url,“?”,“UseServerPrepsmts=false&rewriteBatchedStatements=true”);
setDriverClassName(“com.mysql.jdbc.Driver”);
dataSource.setUsername(用户名);
dataSource.setPassword(密码);
setDataSource(dataSource);
返回jdbc模板;
}
@豆子
公共空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间空间(){
return new isomefacedaoimpl();//如果属性文件中没有错误配置,您应该能够在bean方法中直接使用“someotherproperty”。避免使用@Value
注释多个字段的更好方法是使用环境
抽象
@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"));
}
}
谢谢,环境方法解决了所有问题。