Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call Component or Service from Controller in Spring MVC

I want to save region ( property of authenticated User) in a class. Region list is fetched from Database and stored as a property for each User in Spring Controller Class suppose "A".

Now this region property I want to fetch in spring interceptor "B" and want to validate the region for the user which I am getting as a parameter in each http request to that of stored in region property.

I was suggested to use Service or Component to store region list so that Interceptor B and Controller Class A can both use that Service or Component.

Can any one tell me how to use Service or Component in this case.

like image 418
Avinash Kumar Avatar asked Nov 26 '14 20:11

Avinash Kumar


1 Answers

Your question isn't entirely clear, but I'll try my best.

I think you are saying you want to use the same class in both a Spring MVC HandlerInterceptor as well as a Controller?

You should use Dependency Injection for this:

Annotate the service class with @Service (this lets Spring find your service)

@Service
public class MyRegionService...

Add component-scanning to your application context configuration (this finds the service)

<context:component-scan base-package="com.example.yourapp"/>

Add the service as a class member wherever you need it, and annotate it with @Autowired (this injects the service)

@Controller
public class MyController {

  @Autowired
  MyRegionService myRegionService;
}

and

public class MyHandlerInterceptor extends HandlerInterceptorAdapter {

  @Autowired
  MyRegionService myRegionService;
}
like image 185
Neil McGuigan Avatar answered Sep 22 '22 07:09

Neil McGuigan