So let's say I have a bean in application-context.xml
:
<bean id="foo" class="biz.tugay.FooImpl" />
and I have another module, let's say module thud and in application-context-thud.xml
I will also have:
<bean id="foo" class="biz.tugay.thud.ThudFooImpl" />
So when I run my application with profile thud activated, bean foo will be overriden with biz.tugay.thud.FooImpl
. Up to this point all is ok.
But lets say all I want is something like this:
package biz.tugay
class FooImpl{
void foo(){// Lots of code here};
}
and in the overriden bean all I want to do is:
package biz.tugay.thud
class ThudFooImpl{
void foo(){
if(something..) return;
else {
// Lots of code here
}
};
}
so what I currently do is this:
package biz.tugay.thud
import biz.tugay.FooImpl
class ThudFooImpl extends FooImpl{
void foo(){
if(something..) return;
else {
super.foo();
}
};
}
But the problem is, if FooImpl
has dependencies, I will have to inject the dependencies to the ThudFooImpl
as well. But as you can see from the code, I do not even need those dependencies in ThudFooImpl
.. All I have is a simple if check.
So code will look like this in the xml files:
<bean id="foo" class="biz.tugay.Foo">
<constructor-arg ref="waldo"/>
<property name="baz" ref="baz"/>
<property name="qux" ref="qux"/>
<property name="quux" ref="quux"/>
<property name="corge" ref="corge"/>
</bean>
<bean id="foo" class="biz.tugay.thud.ThudFooImpl">
<constructor-arg ref="waldo"/>
<property name="baz" ref="baz"/>
<property name="qux" ref="qux"/>
<property name="quux" ref="quux"/>
<property name="corge" ref="corge"/>
</bean>
which looks like I am doing something wrong here?
Is there any way to override beans without requiring to inject all the dependencies to the subclassing bean?
I can't say I remember using it myself in practice, but I think it might be the parent
attribute that you're looking for:
An un-tested example using your terms:
<bean id="foo" class="biz.tugay.Foo">
<constructor-arg ref="waldo"/>
<property name="baz" ref="baz"/>
<property name="qux" ref="qux"/>
<property name="quux" ref="quux"/>
<property name="corge" ref="corge"/>
</bean>
<bean id="thudFoo" class="biz.tugay.thud.ThudFooImpl" parent="foo"/>
I expect this won't work exactly, I don't have a project to easily test it with, but hopefully together with the docs it will get you some of the way...
You could make ThusFooImpl
extend FooImpl
by composition rather than inheritance. They should both implement a Foo
interface, and you could inject an instance of FooImpl
into ThudFooImpl
. Then call the injected FooImpl
from the 2nd branch of your if
statement in ThudFooImpl
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.