7

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?

1 Answer 1

14

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:

  1. Talk to the author of the parent class and kindly ask him to change it.

  2. 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).

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks ESala. In my case , the class that I am trying to extend is part of a jar and is defined wiith Component annotation. I want to create a new bean which extends it and overrrides one method.
@PunterVicky I have added the answer to your follow-up question :)
Thanks again , ESala!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.