1

有多个用 @Configuration 注释的类,我想在顶级配置组件中决定在上下文中注册哪个类。

@Configuration
public class FileSystemDataStoreConfiguration {
  public @Bean DataStore getDataStore() {
    return new FileSystemDataStore(withSomeConfigProperties);
  }
}

@Configuration
public class DatabaseDataStoreConfiguration {
  public @Bean DataStore getDataStore() {
    return new DatabaseDataStore(withSomeConfigProperties);
  }
}

@Configuration
public class DataStoreConfiguration {

  // Some arbitrary logic to decide whether I want to load
  // FileSystem or Database configuration.

}

我知道我可以使用 @Profile 在多个配置类中进行选择。但是,我已经使用配置文件来区分环境。配置类的选择与环境无关。

如何在运行时选择要加载的配置类?

我可以拥有多个活动配置文件,例如“Production, WithDatabase”吗?

如果是这样,我如何添加基于属性的配置文件?

4

2 回答 2

2

如果您使用的是 Spring 4,则可以使用新的 @Conditional 注释功能(实际上是用于实现 @Profile 的后端)

于 2014-03-11T15:16:39.707 回答
2

春天,所以有很多方法可以做事!

如果您保留所有注释,则可以使用 @ActiveProfiles 注释,以便启用所需的全部配置文件集:

@ActiveProfiles(profiles = ProfileDefinitions.MY_ENABLED_PROFILE)
@ContextConfiguration(as usual from here...)

您会看到“配置文件”允许设置许多配置文件。您也不需要将配置文件存储为常量,但您可能会发现这很有帮助:

public class ProfileDefinitions {

    public static final String MY_ENABLED_PROFILE = "some-profile-enabled";

    // you can even make profiles derived from others:
    public static final String ACTIVE_WHEN_MY_IS_NOT = "!" + MY_ENABLED_PROFILE;
}

使用上述所有方法,您可以根据配置文件的动态设置有选择地启用各种配置:

@Profile(ProfileDefinitions.MY_ENABLED_PROFILE)
@Configuration
@Import({these will only be imported if the profile is active!})
public class DatabaseDataStoreConfiguration {
}

@Profile(ProfileDefinitions.ACTIVE_WHEN_MY_IS_NOT)
@Configuration
@Import({if any are necessary})
public class DataStoreConfiguration {
}
于 2014-03-18T13:11:58.600 回答