Home > Enterprise >  Spring @DependsOn For Different Profiles
Spring @DependsOn For Different Profiles

Time:05-14

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?

CodePudding user response:

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.

  • Related