Tutorial

Spring @Service Annotation

Published on August 3, 2022
author

Pankaj

Spring @Service Annotation

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 our products

About the authors
Default avatar
Pankaj

author

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.

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!

          Become a contributor for community

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

          DigitalOcean Documentation

          Full documentation for every DigitalOcean product.

          Resources for startups and SMBs

          The Wave has everything you need to know about building a business, from raising funding to marketing your product.

          Get our newsletter

          Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

          New accounts only. By submitting your email you agree to our Privacy Policy

          The developer cloud

          Scale up as you grow — whether you're running one virtual machine or ten thousand.

          Get started for free

          Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

          *This promotional offer applies to new accounts only.