11

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?

IAdapter
  • 62,595
  • 73
  • 179
  • 242
  • 4
    Can't you just use inheritance? Autowiring in base class will work the same way. – Tomasz Nurkiewicz Nov 25 '11 at 14:17
  • 1
    @Tomasz Nurkiewicz I have spring parent bean defined in xml (it has some property's set to "default" values). That is not something I can change. – IAdapter Nov 25 '11 at 14:42
  • I added an answer to further explain my idea. Can you elaborate a little bit more why it does not suit your needs? Why can't you change the parent definition in XML? I'm afraid it is not possible to reference parent from annotation... – Tomasz Nurkiewicz Nov 25 '11 at 15:04

2 Answers2

6

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.

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 5
    Yours example won't work if `base` bean will be define in XML, with or without creating artificial `Bean` class and `Wallace` and `Gromit` will be created by component-scan. – metyl Oct 09 '12 at 14:12
0

Just came across the same Construct.. (a general abstract parent Class which used Beans - with context.xml-declaration for an potential Implementation that was injected by Component-scan)

This is what I could have done in the @Component Class:

@Autowired
public void setBeanUsedInParent(BeanUsedInParent bean) {
   super.setBeanUsedInParent(bean);
}

..what I ended up doing (better, since it makes clear that the injection works on the object not on classes) - and if you are able to modify the parent Class:

// abstract getter in parent Class
public abstract BeanUsedInParent getBeanUsedInParent();

..leave the actual Beans as well as their injection up to the actual implementation (the @Component Class):

@Autowired
private BeanUsedInParent beanUsedInParent;

@Override
public BeanUsedInParent getBeanUsedInParent() {
   return this.beanUsedInParent;
}