0
public abstract class AbstractClass {

    @Bean
    public String getBeanName() {
        return "My Bean";
    }
}

@Configuration
public class MyClass extends AbstractClass  {

    @Bean
    public String getBeanNameWithoutOverriding() {
        return "1 - " + getBeanName();
    }

    @Bean
    public String getSecondBeanNameWithoutOverriding() {
        return "2 - " + getBeanName();
    }
}

Is this right way to declare bean in abstract class and use it or AbstractClass need to be annotated as a component also? I think it does not make sense to annotate it with it since it cannot be instantiated. When I do it like in my example, it works as expected but I couldn't find any documentation about it.

In real case, bean returns ThreadPoolExecutor. I want only one instance of it. And OFC abstract class has more logic in it also. What I'm trying point out is, does it work like this?

Kaepxer
  • 319
  • 3
  • 16
  • Look here: https://stackoverflow.com/q/48440669/421195 or here: https://docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/creating-bean-definitions.html – paulsm4 May 12 '23 at 15:37
  • first thread is not related to what I asked. It may be a better answer for dependency injection in super class. Documentation is giving example about bean visibility. I'm not sure if it has answer for me since I'm not going to use that bean in another class that is not extending abstract class. Doesn't make sense. Also, if it has to have @Configuration on it, how is it working when I compile it? When I debug, I can see method called just once. – Kaepxer May 12 '23 at 15:47
  • The assumptions implied in your question don't make sense. I'm not sure exactly where your confusion lies. Please put your "assumptions" side and carefully re-read the replies here: https://stackoverflow.com/questions/48440669/. Bottom line: Any Spring bean can *INHERIT* from an abstract class... but you're always *INSTANTIATING* one or another *CONCRETE SUBCLASS*. – paulsm4 May 12 '23 at 16:50

0 Answers0