Search code examples
javaspringspring-bean

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.

Solution

  • 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.