开发者

object creation in spring

If I am using spring frame work in my application does creating an object like this Test test = new Test() a bad way for creating an instance? Should I always use the bean config to get the obje开发者_StackOverflow中文版cts/bean that I need? If yes, does that means I should have all the object/bean definition in spring applicationContext xml file?


If you want your object to be managed by Spring (this means that dependencies are injected, among other things) you have to use the ApplicationContext.

Calling Test test = new Test() isn't illegal, or even bad practice. It just means that Spring will have no awareness of this object, and it won't bother autowiring it's dependencies, or doing anything else that you'd expect Spring to do.

You don't necessarily need to use the applicationContext.xml file for ALL of your bean declarations. Many people favor annotations, which allow you to declare beans outside of the applicationContext.xml file.

It's worth nothing that Spring-managed beans are by default singletons (think of Servlets). If you want stateful beans that are Spring aware, you could use an ObjectFactoryCreatingFactoryBean to do something like this:

@Autowired 
private ObjectFactory myWidgetFactory;

public void doStuff() {
   Widget w = myWidgetFactory.getObject();
}

You can read more about this behaviour here:

http://static.springsource.org/spring/docs/3.0.x/api/org/springframework/beans/factory/config/ObjectFactoryCreatingFactoryBean.html


For me there's a big difference between objects that represent components of my application -- services, controllers, DAOs, utilities, etc. -- and objects that represent entities within my application -- Person, Order, Invoice, Account, etc. The former type of objects should absolutely be managed by Spring and injected. The latter type are typically created on the fly by the application, and that frequently will involve calling new. This is not a problem.


Test test = new Test() a bad way for creating an instance?

Yes it is bad practice.

Should I always use the bean config to get the objects/bean that I need?

Yes, if you are using Spring for dependency injection.

If yes, does that means I should have all the object/bean definition in spring applicationContext xml file?

Always! You could use Annotations too.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜