Reputation: 3975
What is the best method to access Service Layer from Controller in Spring MVC? I'm using annotations for SpringMVC.
Earlier I used to get the bean everytime from the bean factory by calling ClassPathXMLApplicationContext(spring-bean-name.xml) in every method of controller.
From the solution to question Accessing Service Layer from custom Controller in Spring MVC I understand that service bean has to be autowired.
However suppose a controller accesses multiple services do we have to inject multiple beans? But that won't be a good practice cause we will have to use a particular service only in 1-2 methods within a controller and its not good to make it a class variable rather than a function variable.
Upvotes: 0
Views: 3418
Reputation: 1397
This is why you have to try to keep all the methods that use the same dependencies together, this is low coupling. The bad practice is not injecting your dependencies as global variables. The bad practice is to not group your methods to make your class less coupled.
Upvotes: 0
Reputation: 653
You can have a static class which instantiates bean factory and then use custom static getBean method of this static class
static class SpringConfig()
{
private static ApplicationContext ctx = null;
static
{
ctx=new ClassPathXmlApplicationContext("context.xml");
}
public static Object getBean(String beanName)
{
return ctx.getBean(beanName);
}
}
Upvotes: 0
Reputation: 27614
You are correct, you need to autowire the services you intend to use. Don't worry about class variable versus local (function) variable, this is how the DI pattern is implemented.
In the strictest OO-design sense, you have a point that you should not declare variables on a class-level unless they are involved in describing the state of an object. DI (Dependency Injection) is, however, a very established pattern on no developer is going to frown upon service beans as autowired class members, regardless of how many methods actually use the service.
On a side-note, doing new ClassPathXMLApplicationContext("spring-bean-name.xml")
in every method is absolutely, 100% the wrong way to do it. That involves creating a new bean-factory and bean-context every time you execute that method which is a big overhead and completely unnecessary. The bean-factory should be created once (if you're in a servlet-engine environment, by using the DispatcherServlet or the ContextLoaderListener).
Upvotes: 3