Difference between @ Service and @ Resource annotation in Spring, @ service @ resource
Differences between @ Service and @ Resource annotations in Spring
1 Preface
Annotation is an indispensable part of spring framework. It helps us get rid of the tedious XML file configuration, but one thing we need to grasp on our own, that is "3 What", that is, "When and Where are annotations used?" In this blog, the author briefly introduces how to properly use the @ Service and @ Resource annotations.
2 Annotations
2.1 @ Service
When we need to define a class as a bean, we can add a @ Service Annotation on the class name of this 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 bean name. In addition, we only use this annotation to mark the bean. If no value is specified, the bean name generated by Spring is the class name, and 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, when assigning values or injecting values to the attribute, you need to add a @ Resource Annotation on the last line of this attribute, that is
@ Servicepublic 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 to this attribute.
3 extension
In Spring 2.5, we provide a wide range of annotations. Here we will introduce four common Annotations:
- @ Service, used to mark the Service layer components (This annotation is usually used for the defined Service layer );
- @ Controller, used to mark control layer components (such as actions in Struts );
- @ Repository: used to mark the data access component, that is, the DAO layer component;
- @ Component refers to components. When components are not classified well, we can use this annotation for annotation.
The above four annotations are based on classes. We can define names or not names. If the name is not defined, Spring uses the bean name by default in the lower-case phrase of the class name. In addition, you can also learn the differences between @ Autowired and @ Resource annotations by reading "Click me, click me, and click me.
Thank you for reading this article. I hope it will help you. Thank you for your support for this site!