Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override bean definition in java config

Tags:

java

spring

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?

like image 728
maks Avatar asked May 08 '14 16:05

maks


People also ask

Can we use @bean without @configuration?

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

What is the use of @configuration in Spring?

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.

How do you define a bean configuration?

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 .

How do I override a configuration class in Spring boot?

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.


1 Answers

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.

  • overriding bean configuration in spring
  • Overriding the bean defined in parent context in a child context
  • Spring's overriding bean
like image 147
Centonni Avatar answered Sep 27 '22 16:09

Centonni