Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

@Component with parent?

Tags:

java

spring

Is there any way to use <bean parent="someParent"> with @Component annotation (creating spring beans using annotation)?

I would like to create spring bean that has "spring parent" using @Component annotation.

is it possible?

like image 815
IAdapter Avatar asked Nov 25 '11 14:11

IAdapter


1 Answers

Following my comment, this piece of XML

<bean id="base" abstract="true">
    <property name="foo" ref="bar"/>
</bean>

<bean class="Wallace" parent="base"/>
<bean class="Gromit" parent="base"/>

is more or less eqivalent to this code (note that I created artificial Base class since abstract beans in Spring don't need a class):

public abstract class Base {
    @Autowired
    protected Foo foo;
}

@Component
public class Wallace extends Base {}

@Component
public class Gromit extends Base {}

Wallace and Gromit now have access to common Foo property. Also you can override it, e.g. in @PostConstruct.

BTW I really liked parent feature in XML which allowed to keep beans DRY, but Java approach seems even cleaner.

like image 51
Tomasz Nurkiewicz Avatar answered Oct 03 '22 00:10

Tomasz Nurkiewicz