Differences between @ Service and @ Resource annotations in Spring

  • 2021-12-09 09:41:29
  • OfStack

Differences between @ Service and @ Resource annotations in Spring

1 Preface

When we use the spring framework, annotations are an "indispensable" part. She helps us get rid of the tedious work of configuring XML files, but there is one point that we need to grasp ourselves, that is, "3 what", that is, "when and where to use annotations?" In this blog post, the author briefly introduces how to use @ Service and @ Resource annotations properly under 1.

2 Notes

2.1 @Service

When we need to define a class as an bean, we can add a @ Service annotation to the class name of this class, that is,


@Service("yeepay")
public class YeepayService(){
 public static void sayHi(){
  System.out.println("Hi , dimension C Fructose !") ; 
 }
}

Here, @ Service ("XXX") is equivalent to defining this class as an bean, where XXX is the name of bean. In addition, we only use this annotation to mark bean. If value is not filled in, the name of bean generated by Spring is the class name, and then the first letter is lowercase.

2.2 @Resource

When we need to define an attribute in a class, and the attribute is an existing bean, we need to add an @ Resource annotation on the top 1 line of the attribute when assigning or injecting the attribute, that is,


@Service
public class YeepayService(){

 @Resource(name="yeePay")
 private YeePay yeePay;

 public static void sayHi(){
  System.out.println("Hi , dimension C Fructose !") ; 
 }
}

Here, @ Resource (name = "XXX") is equivalent to injecting an bean named XXX into this attribute.

3 Extension

In Spring 2.5, it provides us with abundant annotations. Here are four commonly used annotations:

@ Service, which is used to annotate business layer components (this annotation is usually used in the defined Service layer); @ Controller, used to annotate control layer components (such as action in Struts); @ Repository, which is used to annotate data access components, that is, DAO layer components; @ Component refers to components in general. When components are not easy to classify, we can use this annotation to annotate them.

The above four annotations are all class-based, and we can define names or not. When no name is defined, Spring defaults to the name of bean with the class name and lowercase initials. In addition, you can learn the difference between @ Autowired and @ Resource annotations by reading "Point Me, Point Me, Point Me".

Thank you for reading, hope to help everyone, thank you for your support to this site!


Related articles: