I came across this link which explains how a bean can be inherited. Assuming that HelloWorld class in this example is exposed as a bean using @Component annotation , how can create another bean which inherits this bean? Can I use extends to inherit HelloWorld bean and add @Component to the new class in order to extend the existing bean expose it as a new bean with additional features?
The answer is: noSpring's @Component annotation does not have @Inherited on it, so you will need to put the annotation on each component class.
The @inherited in Java is an annotation used to mark an annotation to be inherited to subclasses of the annotated class. The @inherited is a built-in annotation, as we know that annotations are like a tag that represents metadata which gives the additional information to the compiler.
The @interface element is used to declare an annotation. For example: @interface MyAnnotation{}
Annotation is defined like a ordinary Java interface, but with an '@' preceding the interface keyword (i.e., @interface ). You can declare methods inside an annotation definition (just like declaring abstract method inside an interface). These methods are called elements instead.
First you make your abstract configuration, which is achieved by not marking it as @Configuration
, like this:
// notice there is no annotation here
public class ParentConfig {
@Bean
public ParentBean parentBean() {
return new ParentBean();
}
}
An then you extend it, like this:
@Configuration
public class ChildConfig extends ParentConfig {
@Bean
public ChildBean childBean() {
return new ChildBean();
}
}
The result will be exactly the same as if you did this:
@Configuration
public class FullConfig {
@Bean
public ParentBean parentBean() {
return new ParentBean();
}
@Bean
public ChildBean childBean() {
return new ChildBean();
}
}
Edit: answer to the follow-up question in the comment.
If Spring picks up both classes, parent and child, there will be problems with duplicated beans, so you cannot extend it directly. Even if you override methods, the beans from the super-class will also be instantiated by the ParentConfig
.
Since your parent class is already compiled, you have 2 options:
Talk to the author of the parent class and kindly ask him to change it.
Change the @ComponentScan
packages.
To clarify on solution 2:
If the parent class is in the package com.parent.ParentConfig
and the child class is the package com.child.ChildConfig
, you can configure the component scanning so that only classes under com.child
get picked up.
You can specify the component scanning packages using the @ComponentScan("com.child")
annotation on your main configuration file (think application class).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With