【问题标题】:Access to properties from created bean从创建的 bean 访问属性
【发布时间】:2018-04-19 20:21:40
【问题描述】:

我有这样的课程,如下所示:

@Configuration
@PropertySource("classpath:sample.properties")
public class SampleConfig {
 @Value("${attr1.prop}")
 private String attr1;

 @Value("${attr2.prop}")
 private String attr2;
 @Bean
 public SampleService sampleService() {
  return new SampleService(attr1);
 }

 @Bean
 public static PropertySourcesPlaceholderConfigurer placeHolderConfigurer() {
  return new PropertySourcesPlaceholderConfigurer();
 }
}

我创建了带有参数 attr1 的 SampleService bean。是否可以访问我稍后使用 @PropertySource 加载的属性?例如在@Autowired 之后。

这是使用该 bean 的代码:

@Service
public class SuperHotServiceImpl {

   @Autowired
   SampleService sammpleService;

   public void fooFunc() {
      // here I need some magic to get value of attr2.prop
      sammpleService.setAttr(attr2);
   }
}

你能告诉它是否可能吗?谢谢

【问题讨论】:

  • 是什么让您无法在服务中简单地使用 @Value("${attr2.prop}") String attr2 字段?
  • @CoderinoJavarino 电子邮件通知,我需要在运行时在 fooFunction 中更改。

标签: java spring properties javabeans


【解决方案1】:

如果我正确理解您的问题,那么这应该会有所帮助:

@Service
public class SuperHotServiceImpl {
    @Autowired
    private SampleConfig sammpleConfig;

    public void fooFunc() {
        System.out.println(sampleConfig.getAttr2());
    }
}

假设SampleConfig 被注释为@Component 并且您提供了getter。

【讨论】:

  • 当 attr2 为私有时 sampleConfig.attr2 是否可行?
  • 是的,我正在考虑,但我不确定这是否是一个好习惯。
  • 为什么不呢?拆分配置数据及其使用情况是不错的做法。但是您仍然可以按照@CoderinoJavarino 的建议将@Value("${attr2.prop}") String attr2 字段放入服务中。
猜你喜欢
  • 2013-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多