I have a configuration class
@Configuration
public class FooConfig{
@Bean
public FooService fooService() { ... }
@Bean
public AbcService abcService() { ... }
}
That class is defined in a lib that I can't change. I have a project where FooService
is used in many places. In my project I have another configuration class
@Configuration
@Import({
FooConfig.class,
})
public class BarConfig{
@Autowired AbcService abc;
...
}
AbcService
is used here because there are services which depends on that service and those services are declared in BarConfig
. However, FooService
is not used here(it is used only in controllers)
I need to change the implementation of FooService
. Can I define new FooService
bean in BarConfig
? Will it override already present definition which is imported via FooConfig
?
@Bean methods may also be declared within classes that are not annotated with @Configuration. For example, bean methods may be declared in a @Component class or even in a plain old class. In such cases, a @Bean method will get processed in a so-called 'lite' mode.
One of the most important annotations in spring is @Configuration annotation which indicates that the class has @Bean definition methods. So Spring container can process the class and generate Spring Beans to be used in the application. This annotation is part of the spring core framework.
Declaring a bean. To declare a bean, simply annotate a method with the @Bean annotation. When JavaConfig encounters such a method, it will execute that method and register the return value as a bean within a BeanFactory .
To make a configuration in Spring Boot, you need to create a class and annotate it with @Configuration . Usually, in the configuration class, you can define a beans object. But if you want to override built-in configuration, you need to create a new class that extends the built-in class.
You can redefine the same bean name multiple times, the spring container will take the last bean definition processed for a given name to be the one that wins.
In your case, as the core project that contains the configuration you can't change does not depend on any of the beans you define in your project, it will work fine if you redefine the FooService
bean.
there was lot of answers about how to override bean defintions before, you can have a look to have more informations.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With