Spring @Service Annotation with Example

18 Feb, 2022
Spring is one of the most popular Java EE frameworks. It is an open-source lightweight framework that allows Java EE 7 developers to build simple, reliable, and scalable enterprise applications. This framework mainly focuses on providing various ways to help you manage your business objects. It made the development of Web applications much easier than compared to classic Java frameworks and application programming interfaces (APIs), such as Java database connectivity (JDBC), JavaServer Pages(JSP), and Java Servlet. This framework uses various new techniques such as Aspect-Oriented Programming (AOP), Plain Old Java Object (POJO), and dependency injection (DI), to develop enterprise applications. Now talking about Spring Annotation
Spring Annotations are a form of metadata that provides data about a program. Annotations are used to provide supplemental information about a program. It does not have a direct effect on the operation of the code they annotate. It does not change the action of the compiled program. 
There are many annotations are available in Spring Framework. Some of the Spring Framework Annotations are listed below as follows where here we are going to discuss one of the most important annotations that is @ServiceAnnotation
@Required
@Autowired
@Configuration
@ComponentScan
@Bean
@Component
@Controller
@Service
@Repository, etc.
@Service Annotation
In an application, the business logic resides within the service layer so we use the @Service Annotation to indicate that a class belongs to that layer. It is also a specialization of @Component Annotation like the @Repository Annotation. One most important thing about the @Service Annotation is it can be applied only to classes. It is used to mark the class as a service provider. So overall @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.
Procedure
Create a Simple Spring Boot ProjectAdd the spring-context dependency in your pom.xml file.Create one package and name the package as “service”.Test the spring repository
Create a Simple Spring Boot Project
Add the spring-context dependency in your pom.xml file.
Create one package and name the package as “service”.
Test the spring repository
Step 1: Create a Simple Spring Boot Project
Refer to this article Create and Setup Spring Boot Project in Eclipse IDE and create a simple spring boot project. 
Step 2: Add the spring-context dependency in your pom.xml file. Go to the pom.xml file inside your project and add the following spring-context dependency.
XML
<dependency>    <groupId>org.springframework</groupId>    <artifactId>spring-context</artifactId>    <version>5.3.13</version></dependency>
Step 3: In your project create one package and name the package as “service”. In the service, package creates a class and name it as MyServiceClass. This is going to be our final project structure.
Example
Java
// Java Program to Illustrate MyServiceClass // Importing package module to code modulepackage com.example.demo.service;// Importing required classesimport org.springframework.stereotype.Service; // Annotation@Service // Classpublic class MyServiceClass {     // Method    // To compute factorial    public int factorial(int n)    {        // Base case        if (n == 0)            return 1;         return n * factorial(n - 1);    }}
In this code notice that it’s a simple java class that provides functionalities to calculate the factorial of a number. 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.
Step 4: Spring Repository Test
So now our Spring Repository is ready, let’s test it out. Go to the DemoApplication.java file and refer to the below code.
Example 
Java
// Java Program to Illustrate DemoApplication // Importing package module to code fragmentpackage com.example.demo;// Importing required classesimport com.example.demo.service.MyServiceClass;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.context.annotation.AnnotationConfigApplicationContext; // Annotation@SpringBootApplication // Main classpublic class DemoApplication {     // MAin driver method    public static void main(String[] args)    {         AnnotationConfigApplicationContext context            = new AnnotationConfigApplicationContext();        context.scan("com.example.demo");         context.refresh();         MyServiceClass myServiceClass            = context.getBean(MyServiceClass.class);         // Testing the factorial method        int factorialOf5 = myServiceClass.factorial(5);        System.out.println("Factorial of 5 is: "                           + factorialOf5);         // Closing the spring context        // using close() method        context.close();    }}
Output: 
Note: If you are not using the @Service annotation then you are going to encounter the following exception
Exception in thread “main” org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type ‘com.example.demo.service.MyServiceClass’ available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:351)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBean(DefaultListableBeanFactory.java:342)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1172)
at com.example.demo.DemoApplication.main(DemoApplication.java:17)
surindertarika1234
simranarora5sos
kk773572498
Java-Spring
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.