1

I want to declare @Bean in a super abstract class to prevent declaring it for each subclass.

Consider this class hierarchy:

@Configuration
public class Config {
  public static abstract class A {
    @Bean
    public myBean() {
      return new MyBean();
    }
  }
  public static class B extends A {
    // Some stuff here
  }
  public static class C extends A {
    // Some other stuff here
  }
}

I can't do this in Spring Boot 1.5.9 (Spring Framework 4.3.13).

It throws:

org.springframework.beans.BeanInstantiationException: Failed to instantiate foo.bar.A: Is it an abstract class?

Is there a way to prevent duplicating @Bean for each subclass?

eloy_iv
  • 11
  • 3
  • 1
    Possible duplicate of https://stackoverflow.com/questions/48440669/how-to-create-bean-using-bean-in-spring-boot-for-abstract-class – Naveen Kumar May 22 '18 at 08:41
  • Maybe if you move `A` to it's own file. Spring should normally not try to instantiate `A` unless it's explicitly marked as `@Configuration` or `@Component`. – zapl May 22 '18 at 08:56
  • **You cannot create Beans of abstract class** – Mehraj Malik May 22 '18 at 09:57

1 Answers1

0

Currently, your problem is not duplicate beans. The problem is that class A is not annotated with @Configuration. If you add it, it will start without a problem.

The following is the specs for configuration classes. The Spring's @Configuration documentation states -

  • Configuration classes must be provided as classes (i.e. not as instances returned from factory methods), allowing for runtime enhancements through a generated subclass.
  • Configuration classes must be non-final.
  • Configuration classes must be non-local (i.e. may not be declared within a method).
  • Any nested configuration classes must be declared as static.
  • @Bean methods may not in turn create further configuration classes (any such instances will be treated as regular beans, with their configuration annotations remaining undetected).

About that duplicated Beans

Only single Bean will be created. The bean definition will only be loaded and created once :)


Reg
  • 10,717
  • 6
  • 37
  • 54