Solved

Spring, Struts and JPA best practice on defining Service classes

Posted on 2009-07-03
8
826 Views
Last Modified: 2013-11-24
I'm relatively new to Spring and JPA, and was wondering the best practice for using Service classes to interact with Struts Actions.

Currently for every POJO entity bean defined in a Model package, I have a corresponding Service interface, and a Service Implementation class in a Service Package with the @Transactional annotation. To be able to use these in any Struts Action, I have to pass these services as arguments to the Action Bean definition in ApplicationContext.xml.

For instance, take a clases Employee, a class Department, and a class Office. All three classes have their entity bean definition, and individual Service and Service implementation classes. And definitions for all three beans in Application Context, and all are passed to the constructor-arg of an EmployeeAction bean.

Is this the recommended approach or is there a simpler way to do this? It seems that going through all these to only use a Department for a pull down list in a JSP, and assign the Department object to the Employee, and persist it, is a bit overkill.

Any hints aprreciated.
 
0
Comment
Question by:jamve
  • 4
  • 2
8 Comments
 
LVL 40

Accepted Solution

by:
mrjoltcola earned 250 total points
ID: 24773589
More often I see (and use) Spring wire-by-name so there is no need to specifically add each one to the applicationContext.xml for each action. Spring will do it for you, by examining the properties of each POJO. Just declare a setter method in the Action class for the service bean, and it will get called. I use wire-by-name exclusively.

Also, if there are services that you use in all or most Actions, use inheritance to declare the setters / properties in base Action classes. In my apps I commonly use base classes for a User domain object and UserService class, because 99% of the actions require an authenticated User to be in context. The mechanism for managing the User object in the session is hidden in the base class. Not sure if you mean Struts1 or 2, but in Struts2 I use the SessionAware interface to hide those things in the base classes, so there is no explicit session code in the leaf Action classes.

0
 
LVL 40

Assisted Solution

by:mrjoltcola
mrjoltcola earned 250 total points
ID: 24773626
I put my services in the spring-service.xml class, and Spring picks them up and wires them if Spring is the container for the Action classes.

Sample Action class below.
First, applicationContext.xml snippet...
 

<beans default-autowire="byName">

	

	<import resource="spring-dao.xml"/>

	<import resource="spring-service.xml"/>

 

[...snipped...]

 

</beans>

 

 

 

 

// Then my action class (Struts2)

 

public class MyActionSupport extends ActionSupport implements SessionAware, Preparable {

 

	protected UserService userService;

	protected Map session;

	protected User user;

 

	// Called by Struts2 to let user setup the action before execution

	public void prepare() {

		// user will always be available to this action

		user = (User)session.get(User.SESSION_KEY);

	}

	

	public User getUser() {

		return user;

	}

 

	public Map getSession() {

		return session;

	}

 

	public void setSession(Map session) {

		this.session = session;

	}

 

        // Called by Spring autowiring

	public void setUserService(UserService userService) {

		this.userService = userService;

	}

	

}

Open in new window

0
 

Author Comment

by:jamve
ID: 24774167
mrjoltcola: thanks for your helpful input,
and with respect to auxiliary clases, say Department, Office, and their corresponding services, you would inherit this from the UserService?
I'm using struts2.1.6, so far no need to extend ActionSupport, and SessionAware, i think this is no longer required, correct?
Also, spring framework 2.0.8, doesn't seem to require the spring-services.xml.
0
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24774195
>>and with respect to auxiliary clases, say Department, Office, and their corresponding services, you would inherit this from the UserService?

Department and Office are domain classes.

DepartmentService and OfficeService might be service classes.

I do not see any inheritance between UserService and the others you mentioned. We typically design a service for each functionality area of the application.

>>I'm using struts2.1.6, so far no need to extend ActionSupport, and SessionAware, i think this is no longer required, correct?


It is not required but it is recommended and useful. It provides common constants and some other convenience methods.

You are also not required to implement the *Aware interfaces, you can write explicit code instead, it is up to you. I find those interfaces help designing clean Action hierarchies for reuse.

spring-services.xml in my example is simply an include file that lists my service beans. I could have put them directly in applicationContext.xml. Same for spring-dao.xml

Using the include files helps reduce the clutter.
0
 

Author Comment

by:jamve
ID: 24774241
Here is a sample of the code in the UserAction, i was wondering if there was a simpler way to do this instaed of passing all those services to the constructor, and also in the save() method, to be converting ids into objects before saving.




    public UserAction(UserService usvc, DepartmentService dsvc, RegionService rsvc, OfficeService osvc) {

        this.service = usvc;

        this.dservice = dsvc;

        this.rservice = rsvc;

        this.oservice = osvc;

    }

    

    public String execute() {

    	this.users = service.findAll();

    	this.departments = dservice.findAll();

    	    	

    	this.countries = rservice.findLevel(Region.Level.COUNTRY);
 

    	this.offices = oservice.findAll();

    	

        return Action.SUCCESS;

    }

    

	public String save() {

		this.service.save(user);
 

		country = rservice.find(Integer.parseInt(countryid.trim()));

		user.setCountry(country);
 

		country = rservice.find(Integer.parseInt(nationalityid.trim()));

		user.setNationality(country);

		

		state = rservice.find(Integer.parseInt(stateid.trim()));

		user.setState(state);
 

		department = dservice.find(Integer.parseInt(deptid.trim()));

		user.setDepartment(department);
 

		office = oservice.find(Integer.parseInt(officeid.trim()));

		user.setOffice(office);

		

		this.service.save(user);

Open in new window

0
 
LVL 40

Expert Comment

by:mrjoltcola
ID: 24996918
I did not notice the reply here but I did originally provide the working sample of a Struts2 action for wire-by-name. The asker asked a followup, but the answer is what I already posted, except I just probably needed to attempt to explain again, so I will do so for the PAQ.

Hi jamve,

My 1st and 2nd posts and code sample explains and demonstrates the answer to your followup question. If you use wire-by-name, then all you need to do is make sure the Action class has a setter for that property bean, and Spring will set it for you. Please reread those posts.

Where your code has a constructor:

  UserAction(UserService usvc, DepartmentService dsvc, RegionService rsvc, OfficeService osvc)

My sample uses a default constructor, but shows that you must provide:

   void setUserService(UserService userService) ...

and so forth. Spring will set it for you, no need to add the parameter in the spring config file. Also reread the part where I suggest using inheritance so you can add these services to the base class of your actions, so each new action does not need the setter/getter explicitly. It works very well once you get the hang of it.

I am only objecting to the Cleanup Admin's recommendation to delete, since I think the question was answered, however I am sorry I did not followup to your last question to clarify.

mrjoltcola
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Are you developing a Java application and want to create Excel Spreadsheets? You have come to the right place, this article will describe how you can create Excel Spreadsheets from a Java Application. For the purposes of this article, I will be u…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

22 Experts available now in Live!

Get 1:1 Help Now