'Spring @DependsOn For Different Profiles

I have two different beans for the same class with different configurations depending on the given profile.

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

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

I have another bean that depends on VaultPropertySource instance.

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

    private final VaultPropertySource vaultPropertySource;

The problem is bean names are different and it only works on the first instance. How can I make it work on both profiles? Can I make it depend on the bean class instead of bean name?



Solution 1:[1]

Separate the profiles not on the bean but on the configuration 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
    }
}

That probably helps.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 pat_b13