java - 如何在 Spring 中使用基于注释的属性

标签 java spring annotations

我想在 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/

相关文章:

Java 传递依赖问题没有可行的解决方案

java - 为什么 Chrome 不渲染从套接字输出流获取的页面? java

Java - 内部类构造函数 - 仅允许外部类

java - 如何让 Jackson mixin 与私有(private)字段一起工作?

php - API 平台 : Change description of an endpoint

java - Hadoop 单节点集群 - 进程未运行

model-view-controller - 使用 spring 3 注释,jsr303 既没有获取 BindingResult 也没有获取 bean 名称 'dataForm' 的普通目标对象

java - Spring 的 AuthenticationManager 未正确注入(inject)

java - 内存中的陈旧对象(mysql、spring 3、hibernate)

spring - 如何复制Spring的component-scan