0

I want to know whether I can use object of service layer marked with @Service annotation and call one of its method in non mvc-spring class ?

Say there is a method getUsers() in service layer which calls getUsers() of Dao layer. In order to use it in contoller I have to add the @Autowired-annotation in the service layer instance. But if I want to use the class method getUsers() in non-mvc class, how can I do that?

gsamaras
  • 71,951
  • 46
  • 188
  • 305
u12345
  • 389
  • 2
  • 8
  • 17

1 Answers1

0

In order to use a service, that object must be container managed. That is, this object's life cycle must be managed by Spring (creation, destruction, initialisation,...).

So to inject an instance of your service in an object, it must be a Spring bean too (Service, Component, Controller...).

So, it may be an MVC object, but it doesn't have to.

On the other hand, there is another alternative: use the annotation @Configurable.

An object with this annotation can be application managed but Spring, using byte code aspects, can inject it's dependencies. So although you create the object with a new statement, Spring instruments this call and resolve all the annotated dependencies.

Read this for more detail:

http://docs.spring.io/spring/docs/3.0.0.M3/spring-framework-reference/html/ch08s08.html

jfcorugedo
  • 9,793
  • 8
  • 39
  • 47
  • Why it needs to be container managed? If my application get hold of the App Context, get the service bean from app context and invoke it, it should still work. – Adrian Shum May 04 '15 at 08:00
  • Yes, of course, but in that case your object is **application managed**, because you're in charge of resolving its dependencies (using app context or whatever you want). If the object is **container managed**, spring is in charge of resolving the dependencies of that object when a new instance is created. – jfcorugedo May 04 '15 at 08:07