Differences between @Service and @Resource annotations in Spring

Time:2019-10-11

Differences between @Service and @Resource annotations in Spring

1 Preface

When we use spring framework, annotations are an “indispensable” part. She helps us get rid of the tedious task of configuring XML files, but one thing we need to grasp is “3He”, that is, “When, Where and Where to Annotate?” In this blog post, the author briefly introduces how to use the @Service and @Resource annotations appropriately.

2 Notes

2.1 @Service

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

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

Here, @Service (“XXX”) is equivalent to defining this class as a bean, where XXX is the name of the bean. In addition, we mark beans with this annotation only. If we don’t fill in value, the bean name generated by Spring takes the class name and lowercase the initial letter.

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 previous line of the attribute, that is, when assigning or injecting the attribute.

@Service
public class YeepayService(){

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

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

Here, @Resource (name= “XXX”) is equivalent to injecting a bean named XXX into the property.

3 extension

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

  1. @ Service, which is used to annotate business layer components (commonly defined service layer uses this annotation);
  2. @ Controller, used to annotate control layer components (such as actions in Struts);
  3. @ Repository, used to annotate data access components, namely DAO layer components;
  4. @ Component is a general term for components. When components are not classified properly, we can use this annotation to annotate them.

These four annotations are class-based. We can define names or not. When a name is not defined, Spring defaults to the name of a bean with a class name and a lowercase initial phrase. In addition, you can also learn the difference between @Autowire and @Resource annotations by reading “click me, click me, click me”.

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