The functionality of @Service annotation in Spring

Mert Mertce picture Mert Mertce · Mar 31, 2015 · Viewed 9.2k times · Source

This is a kind of "what is @Service annotation?" question, but with another approach. Because, I am not sure what is going on here:

I have a controller class:

@Controller
public class GreetingController {
    @Autowired
    SomeBean someBean;

    @MessageMapping("/msg")
    public String msg() {
        someBean.handleMsg();
        return "";
    }
}

From within someBean.handleMsg I try to send a response to a destination. Some thing like this:

public class SomeBean {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    public handleMsg() {
        messagingTemplate.convertAndSend("/topic/someTopic", "Response");
    }
}

There are two versions of configuration.

  1. SomeBean is configured in .xml:

Like:

< bean id="someBean" class="package.SomeBean"></bean>
  1. SomeBean is annotated as service (in the first one it does not have):

Like:

@Service
public class SomeBean{...}
  • Please note that in these two cases there is not any problem about injections etc. In both cases the client is successfully subscribed, sent message, and message is handled.

The only difference is:

  • When SomeBean has @Service annotation, it successfully responses to the client, but when it does NOT have, the client does not receive the response message, although there is not any exception.

Here is the question:

  • What actually does @Service in this case? Could someone please explain what is going on here?

Answer

ksokol picture ksokol · Mar 31, 2015

From a technical point of view there is little difference between @Service and xml based configuration. Both methods are used for declaring Java classes as Spring beans which are managed and used for dependency injection inside a Spring based application.

Main difference is that a class annotated with @Service is a candicate for autodetection during classpath scanning. With annotation driven dependency injection you don't need to declare every Java class as a Spring bean inside your xml configuration.

That is what the javadoc says:

Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."

May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.

This annotation serves as a specialization of @Component, allowing for implementation classes to be autodetected through classpath scanning.