PDA

View Full Version : Trying to better understand IOC using DAO's as an example



droux
Aug 23rd, 2004, 04:24 AM
I have this in a Struts action. For some reason it feels "wrong" to me.

CategoryDAO dao = (CategoryDAO) WebApplicationContextUtils.getWebApplicationContex t(this.servlet.getServletContext()).getBean("CategoryDAO");
Category category = dao.createCategory(form.getName());

Both CategoryDAO and Category are interfaces.

I would have preferred using a prototype bean so that I can do something like this:

Category category = ...getBean("Category");

But then I need to setup the bean using:

category.setName(form.getName());

If there are a lot of properties I need to set this is going to get tedious.

Somewhere I am not understanding IOC very well. Please help!

irbouho
Aug 24th, 2004, 10:31 AM
CategoryDAO dao = (CategoryDAO) WebApplicationContextUtils.getWebApplicationContex t(this.servlet.getServletContext()).getBean("CategoryDAO");

You can use org.springframework.web.struts.ActionSupport, then the previous line will read


CategoryDAO dao = (CategoryDAO) webApplicationContext.getBean("CategoryDAO");



I would have preferred using a prototype bean so that I can do something like this:

Category category = ...getBean("Category");

But then I need to setup the bean using:

category.setName(form.getName());

why would you use Spring DI to create your business objects? It is (I think) easier to use


Category category = new CategoryImpl ();



But then I need to setup the bean using:

category.setName(form.getName());

well, you can use Jakarta Commons BeanUtils. Struts heavely uses/recommends it


BeanUtils.copyProperties (category, form);

no additional jars will be needed as struts requires BeansUtils.

Martin Kersten
Aug 27th, 2004, 10:06 AM
I would have preferred using a prototype bean so that I can do something like this:

Category category = ...getBean("Category");

But then I need to setup the bean using:

category.setName(form.getName());

If there are a lot of properties I need to set this is going to get tedious.


I think this isn't a good way to utilize prototype beans. I think your code would benifit from using a factory.

Like this:


MyFactory factory=(MyFactory)context.getBean("MyFactory");


Category category=getFactory().createCategory("name");

So your factory can be set up properly using Spring and also decouple implementation and usage. [/code]