التعليق الخاص بـ Spring @Service هو تخصص لتعليق @Component. يمكن تطبيق تعليق خدمة Spring فقط على الفئات. يُستخدم لتمييز الفئة كمزود خدمة.
الربيع @Service تعليق
تعليق الربيع @Service يُستخدم مع الفئات التي توفر بعض الوظائف التجارية. ستقوم سياق الربيع بالكشف التلقائي عن هذه الفئات عند استخدام التكوين القائم على التعليقات وفحص مسار الفئة.
مثال الخدمة
لنقم بإنشاء تطبيق ربيع بسيط حيث سنقوم بإنشاء فئة خدمة الربيع. قم بإنشاء مشروع maven بسيط في Eclipse وأضف تبعية النواة الربيع التالية.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.6.RELEASE</version>
</dependency>
ستبدو هيكلية مشروعنا النهائية كما في الصورة أدناه. لنقم بإنشاء فئة خدمة.
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;
}
}
تنويه أنها فئة جافا بسيطة توفر وظائف لإضافة وطرح عددين. لذلك يمكننا أن نسميها مزود خدمة. لقد قمنا بتعليقها بتعليق @Service حتى يمكن لسياق الربيع اكتشافها تلقائيًا ويمكننا الحصول على مثيلها من السياق. دعونا ننشئ فئة رئيسية حيث سننشئ سياق الربيع المدعوم بالتعليقات ونحصل على مثيل من فئة الخدمة الخاصة بنا.
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);
// إغلاق سياق الربيع
context.close();
}
}
مجرد تنفيذ الفئة كتطبيق جافا، ستنتج الناتج التالي.
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
إذا لاحظت فئتنا MathService، لقد قمنا بتحديد اسم الخدمة باسم “ms”. يمكننا الحصول على مثيل MathService
باستخدام هذا الاسم أيضًا. سيظل الناتج هو نفسه في هذه الحالة. ومع ذلك، سنضطر إلى استخدام التحويل الصريح.
MathService ms = (MathService) context.getBean("ms");
هذا كل شيء لمثال سريع على تعليق @Service من الربيع.
يمكنك تنزيل رمز المشروع المثالي من مستودعنا على GitHub.
المرجع: وثائق الواجهة البرمجية للتطبيقات
Source:
https://www.digitalocean.com/community/tutorials/spring-service-annotation