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?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
First you make your abstract configuration, which is achieved by not marking it as
@Configuration
, like this:An then you extend it, like this:
The result will be exactly the same as if you did this:
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 packagecom.child.ChildConfig
, you can configure the component scanning so that only classes undercom.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).