jeudi 21 octobre 2021

Bean annotated abstract method - Factory method implementation with spring

Let's get quickly to the real thing. We have 6 classes as described below. Classes A,B,C implement the Factory Method design pattern while the caller and consumer is expected to be the spring (instantiating the E,F instances with the factory methods in B,C).

I would expect that @Bean is derived to the implementation of the abstract method in B,C subclasses. Such that once spring instantiates B,C, it will instantiate also the implementation of the abstract method in both of the classes. Which causes me to expect to have beans for E and F.

However, spring instantiates only E and skips instantiation of F. (which is very strange. I would expect it to either work as I thought, or to throw an Exception for trying to instantiate a bean with the same name which is derived from the method name)

Would appreciate a lot your input guys, Thanks,

public abstract class D
{

}

public class E extends D
{

}

public class F extends D
{

}


public abstract class A
{
  @Bean
  protected abstract D createService();
}

@Configuration
public class B extends A
{
  @Override
  protected D createService()
  {
    return new E();
  }
}

@Configuration
public class C extends A
{
  @Override
  protected D createService()
  {
    return new F();
  }

}

Aucun commentaire:

Enregistrer un commentaire