Solved

Spring, Struts and JPA best practice on defining Service classes

Posted on 2009-07-03
8
825 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 40

Expert Comment

by:mrjoltcola
Comment Utility
>>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
Comment Utility
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
Comment Utility
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

Threat Intelligence Starter Resources

Integrating threat intelligence can be challenging, and not all companies are ready. These resources can help you build awareness and prepare for defense.

Join & Write a Comment

After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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 different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

743 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

8 Experts available now in Live!

Get 1:1 Help Now