繁体   English   中英

从创建的bean访问属性

[英]Access to properties from created bean

我有该课程,如下所示:

@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);
   }
}

你能告诉我怎么可能吗? 谢谢

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM