Spring @DependsOn 对于不同的配置文件

Spring @DependsOn For Different Profiles

我有两个不同的 bean 用于相同的 class,根据给定的配置文件具有不同的配置。

@Bean
@Profile("!local")
public VaultPropertySource vaultPropertySource(ConfigurableApplicationContext context)

@Bean
@Profile("local")
public VaultPropertySource vaultPropertySourceLocal(ConfigurableApplicationContext context)

我有另一个依赖于 VaultPropertySource 实例的 bean。

@Component
@RequiredArgsConstructor
@DependsOn({"vaultPropertySource"})
public class VaultPropertyReader {

    private final VaultPropertySource vaultPropertySource;

问题是 bean 名称不同,它只适用于第一个实例。我怎样才能让它在两个配置文件上工作?我可以让它依赖于 bean class 而不是 bean 名称吗?

不在 bean 上而是在配置上分离配置文件 class:

@Configuration
@Profile("!local")
class VaultConfiguration {

    @Bean
    public VaultPropertySource vaultPropertySource(ConfigurableApplicationContext context) {
        // return real PropertySource
    }
}

@Configuration
@Profile("local")
class LocalVaultConfiguration {

    @Bean
    public VaultPropertySource vaultPropertySource(ConfigurableApplicationContext context) {
         // return local PropertySource
    }
}

这可能有帮助。