Tutorial

Spring @Service Annotation

Published on August 3, 2022
Default avatar

By Pankaj

Spring @Service Annotation

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Spring @Service annotation is a specialization of @Component annotation. Spring Service annotation can be applied only to classes. It is used to mark the class as a service provider.

Spring @Service Annotation

Spring @Service annotation is used with classes that provide some business functionalities. Spring context will autodetect these classes when annotation-based configuration and classpath scanning is used.

Spring @Service Example

Let’s create a simple spring application where we will create a Spring service class. Create a simple maven project in Eclipse and add following spring core dependency.

<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-context</artifactId>
	<version>5.0.6.RELEASE</version>
</dependency>

Our final project structure will look like below image. spring service annotation example Let’s create a service class.

package com.journaldev.spring;

import org.springframework.stereotype.Service;

@Service("ms")
public class MathService {

	public int add(int x, int y) {
		return x + y;
	}
	
	public int subtract(int x, int y) {
		return x - y;
	}
}

Notice that it’s a simple java class that provides functionalities to add and subtract two integers. So we can call it a service provider. We have annotated it with @Service annotation so that spring context can autodetect it and we can get its instance from the context. Let’s create a main class where we will create the annotation-driven spring context get the instance of our service class.

package com.journaldev.spring;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class SpringMainClass {

	public static void main(String[] args) {
		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
		context.scan("com.journaldev.spring");
		context.refresh();

		MathService ms = context.getBean(MathService.class);

		int add = ms.add(1, 2);
		System.out.println("Addition of 1 and 2 = " + add);

		int subtract = ms.subtract(2, 1);
		System.out.println("Subtraction of 2 and 1 = " + subtract);
		
		//close the spring context
		context.close();
	}

}

Just execute the class as a Java application, it will produce following output.

Jun 05, 2018 3:02:05 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 15:02:05 IST 2018]; root of context hierarchy
Addition of 1 and 2 = 3
Subtraction of 2 and 1 = 1
Jun 05, 2018 3:02:05 PM org.springframework.context.support.AbstractApplicationContext doClose
INFO: Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@ff5b51f: startup date [Tue Jun 05 15:02:05 IST 2018]; root of context hierarchy

If you notice our MathService class, we have defined the service name as “ms”. We can get the instance of MathService using this name too. The output will remain same in this case. However, we will have to use explicit casting.

MathService ms = (MathService) context.getBean("ms");

That’s all for a quick example of Spring @Service annotation.

You can download the example project code from our GitHub Repository.

Reference: API Doc

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about us


About the authors
Default avatar
Pankaj

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
September 4, 2021

What if i remove @Service annotation still program works?

- ramoji

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 28, 2020

    What if you remove @Service and replace it with @Component, will it work? Just want to know the difference between these two…

    - Madan

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      November 23, 2019

      Nice work, very helpful

      - Kasyoka

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 25, 2018

        What is the difference with your example and others that use @Autowired to get an instance of their service class? Does not using @Autowired help with application startup time?

        - Matt

          Try DigitalOcean for free

          Click below to sign up and get $200 of credit to try our products over 60 days!

          Sign up

          Join the Tech Talk
          Success! Thank you! Please check your email for further details.

          Please complete your information!

          Get our biweekly newsletter

          Sign up for Infrastructure as a Newsletter.

          Hollie's Hub for Good

          Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

          Become a contributor

          Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

          Welcome to the developer cloud

          DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

          Learn more
          DigitalOcean Cloud Control Panel