day0ops
day0ops

Reputation: 7482

Overriding a Spring bean

In a library that Im using it has the following bean defined.

package co.random.core;

@Service
public class ApiEndpoints {

    @Value("${testApi}")
    private String testApi;

    public String getTestApi() {
        return testApi;
    }
}

This is then injected in another part of the library as,

@Autowired
ApiEndpoints apiEndpoints;

Is there anyway to override this bean ?

I tried the following in my code,

@Configuration
public class ApiConfiguration {

    @Primary
    @Bean(name = "apiEndpoints")
    public CustomEndpoints getCustomApiEndpoints() {
        return new CustomEndpoints();
    }
}

But this would throw the error,

Field apiEndpoints in co.random.core.RandomService required a bean of type 'co.random.core.ApiEndpoints' that could not be found.

Upvotes: 0

Views: 80

Answers (1)

Gustavo Passini
Gustavo Passini

Reputation: 2668

That bean was overridden, but the new bean you defined doesn't respect the type expected to be autowired. Your bean must be of type (or extend) ApiEndpoints.

Upvotes: 2

Related Questions