Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a bean from the abstract configuration class in a configuration class imported in the class implementing the abstract one

I have an abstract configuration class Abs that is implemented by Impl

Abs has a bean ImportantBean

We import a Imprt config. class to Impl and I need to use the ImportantBean in Imprt

How can I do that?

IntelliJ says it cannot be autowired

something like:

@Configuration 
@Import(Imprt.class)
public class Impl extends Abs {}

@Configuration
public abstract class Abs{
  @Bean
  public ImportantBean importantBean(){
  return new ImportantBean();}
}

@Configuration
public class Imprt{
  @Autowired
  private ImportantBean importantBean;
}
like image 346
Vitalie Avatar asked Dec 20 '25 04:12

Vitalie


1 Answers

Your Imprt configuration class has no idea while autowiring as to where to get ImportantBean from. You also cannot ensure that when application context is built and beans have been loaded in Spring container (I am assuming you are using Spring framework), ImportantBean should already be present before building Imprt

For configuration class Imprt to receive ImportantBean,

you need to @Import Impl class to Imprt, the code should be implemented like illustrated below-

@Configuration
// @Import(Imprt.class) --> removed this
public class Impl extends Abs {}

@Configuration
public abstract class Abs{
  @Bean
  public ImportantBean importantBean(){
  return new ImportantBean();}
}

@Configuration
@Import(Impl.class) // ---> added new import here
public class Imprt{
  @Autowired
  private ImportantBean importantBean;
}
like image 50
Vishal Avatar answered Dec 21 '25 17:12

Vishal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!