Is there any way to use
with @Component annotation (creating spring beans using annotation)?
I would like to create sprin
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;
}
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.