Solved

Spring, Struts and JPA best practice on defining Service classes

Posted on 2009-07-03
8
830 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
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 
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

Webinar: Aligning, Automating, Winning

Join Dan Russo, Senior Manager of Operations Intelligence, for an in-depth discussion on how Dealertrack, leading provider of integrated digital solutions for the automotive industry, transformed their DevOps processes to increase collaboration and move with greater velocity.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
why cannot we forward request once the response is committed 2 46
javap bin 2 40
Which non-HTML GUI front end to use with Java? 3 24
Java class and jar 3 22
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Viewers will learn about the regular for loop in Java and how to use it. Definition: Break the for loop down into 3 parts: Syntax when using for loops: Example using a for loop:

856 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