After setting up the bean in the xml, how to you instantiate the object?
Once you have wired up the bean in the xml file, how to you instantiate the object?
Is it just like:
Myobject myObject = new MyObject();
And spring under the co开发者_JS百科vers will perform the lookup based on the type?
Or do you have to use the applicationContext?
I believe this is what you are looking for -> http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/beans.html#beans-factory-client
Essentially it boils down to the getBean()
method:
MyObject obj = (MyObject) ctx.getBean("myObject");
Of course, in web context, or in some other environment, you might get the ctx (spring context) from elsewhere, so you won't need to create it manually.
You can also get the object by getting the application context and calling getBean:
ApplicationContext appContext =
WebApplicationContextUtils.getRequiredWebApplicationContext( servletContext );
return appContext.getBean( beanName );
You can get your servlet context by implementing ServletContextAware
and creating the proper setter in your code.
When your application server starts, Spring will do the instantiation for you. And will also "inject" the object in your class.
So, in order for the injection to happen, you will either have to write a setter method (which Spring will call once the object is instantiated)
public class MyClass{
private MyObject myObject;
public void setMyObject(MyObject _myObject){ //Spring will call this method
this.myObject = _myObject;
}
}
or you can have a constructor based injection
public class MyClass{
private MyObject myObject;
public MyClass(MyObject _myObject){ //Spring will call this constructor
this.myObject = _myObject
}
}
EDIT: Thanks for pointing that out Peter D
In your XML config file you will have to do something like:
<bean name="myObject" class="mypackage.MyObject"/>
<bean name="myClass" class="mypackage.MyClass">
<property name="myObject" ref="myObject"/>
</bean>
Hope this helps!
The way you described it, it won't work. Spring won't modify how normal objects are created. To make use of Spring injection, i.e. to get a reference to a Spring bean, you can:
- get the bean from the application context object by name
- let Spring do its job with @Autowired annotations, or auto autowiring :)
- configure injections explicitly in xml
All in all, to get a bean, you must not create it, but ask Spring to deliver it to you.
The magic of dependency-injection is that you don't need to look-up the reference, althought you could do it programmatically.
<bean name="myObject" class="x.y.MyObject"/>
<bean name="anotherObject" class="x.y.Foo">
<property name="myObjectProperty" ref="myObject"/>
</bean>
In addition, you could define if the object should be 'singleton' or prototype (one instance for each request).
I hope it helps you
精彩评论