代码之家  ›  专栏  ›  技术社区  ›  LIvanov

在创建其他bean之前,如何在SPRING中注入额外的属性源?

  •  0
  • LIvanov  · 技术社区  · 8 年前

    我正在写一个库,它将被spring boot项目使用。我想在启动项目中注入 SpringEnvironment 我从互联网上获取的房地产资源。

    @Configuration
    public class MyCustomConfiguration {
    
      @Bean
      BeanDefinedAbove above() { /* do some work */ }
    
      @Bean
      @ConditionalOnBean(BeanDefinedAbove.class)
      SmartInitializingSingleton propertySourceSetting(ConfigurableEnvironment env, BeanDefinedAbove bean) {
        return () -> { 
          PropertySource source = bean.getPropertySourceDownloadedFromTheInternet();
          env.getPropertySources().addFirst(source);
        }
      }
    }
    

    在我客户的项目中,当我调试此代码时,会发生以下两种情况之一:

    1. above() 被称为
    2. 用户的 @Service 或 @Controller
    3. propertySourceSetting(...) 被称为

    或

    1. 用户的 或 @控制器 被称为
    2. 以上() 被称为
    3. 属性资源设置(…) 被称为

    BeanDefinedAbove 豆子,这是正常的 @服务 以上() .

    EnableAutoConfiguration 在 META-INF/spring.factories .

    那么,如何确保 propertySourceSetting(..) 在用户的 @服务 和 @控制器

    1 回复  |  直到 8 年前
        1
  •  0
  •   Diego    8 年前

    我给你三个选择。

    (这是一种糟糕的方法,但解决方法很快)

    为什么这样不好? 这并不能保证秩序。Spring根据依赖关系和其他一些条件决定创建顺序。这就是为什么它“可能”会起作用:)

    创建一个主类来引导Spring引导初始化(启动Spring引导的旧方法)。

    public static void main(String[] args) throws Exception {
       SpringApplication application = new SpringApplication(MyApplication.class);
       // ... add property source here before start
       application.run(args)
     }
    

    https://www.baeldung.com/spring-boot-main-class

    在该主类中,您将添加propertysource,有点像这样:

    SomeClassThatRetrievesProperties propRetriever = new SomeClassThatRetrievesProperties ();
    Map<String,String> properties = propRetriever.getAllPropertiesAsMap(); 
    application.setDefaultProperties(properties);
    

    选项3

    这样你就可以完全控制,但我们知道你可能会破坏一些重要的东西。