开发者

Instantiating dependencies in spring

Hi If Class A is instantiated by spring. In class A i am Instantiating another object of class B ( regular intantiation using new operator) Can i instantiate the dependencies of class B just from insantiating class A??

class A{
    Xdao xDao;
    B bvar = new B();
}

Class B {
    Ydao yDao;
}

Is there a way to directly inject the dependency ob class B while instantiating class A??

is there something like: ( dependecy attribute is just an example)

<bean id="classA"  dependecy="classB"> 
    <property name="xDao" ref="xDao" /> 
</bean> 

<bean id="classB"  > 
    <property name="yDao" ref="xDao" /> 
</bean> 

thanks in advance.

I want to avoid putting another propert开发者_如何学Goy (or constructor) to set for nested call to class B as I don't want to change existing code.


You should let Spring handle all the instantiation and injection. This means that you should inject classB to classA:

<bean id="classA"> 
    <property name="xDao" ref="xDao" /> 
    <property name="bvar" ref="classB" /> 
</bean> 

<bean id="classB"> 
    <property name="yDao" ref="xDao" /> 
</bean>

And, get rid of your new B():

class A {
    Xdao xDao;
    B bvar;
}

class B {
    Ydao yDao;
}


The moment you call "new", that object is not under Spring's control.

Inject or call "new" - it's one or the other.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜