كيف تعمل التهيئة التلقائية في Spring Boot
التهيئة التلقائية هي قلب Spring Boot—فهي تُسجل Beans تلقائياً بناءً على الأصناف الموجودة في مسار الأصناف، مما يتيح لك اتباع مبدأ "الاصطلاح على التهيئة".
1. ما ستتعلمه
@EnableAutoConfigurationوآلية تحميل التهيئة التلقائية- التعليقات الشرطية:
@ConditionalOnClass/@ConditionalOnMissingBean/@ConditionalOnProperty - خطوات إنشاء Starters مخصصة واصطلاحات التسمية
- استخدام وضع
--debugلعرض تقرير التهيئة التلقائية @SpringBootApplication(exclude = {...})استبعاد تهيئات تلقائية محددة
2. قصة حقيقية من مطوّر إطار عمل
(1) نقطة الألم: الاضطرار لكتابة مجموعة من إعدادات التهيئة في كل عملية تكامل
يحتاج فريق Alice إلى دمج SDK دفع جديد في OrderFlow. في كل مرة يدمجون مكوناً جديداً، يجب عليهم كتابة صنف @Configuration، والإعلان عن Beans، وتهيئة الخصائص، والتعامل مع التحميل الشرطي. يعمل Bob، أحد أعضاء الفريق، حتى وقت متأخر من الليل بسبب تعارضات Beans والتبعيات الدائرية؛ استغرق تكامل Redis وحده ثلاثة أيام.
(2) حلول التهيئة التلقائية
Spring Boot Starter يُبسّط "دمج مكون" إلى "إضافة تبعية":
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
بمجرد إضافة هذه التبعية، يتم تهيئة كل من مصنع اتصال Redis وRedisTemplate تلقائياً.
(3) العوائد
بعد أن أنشأت Alice الـ Starter المخصص لـ OrderFlow، يمكن للأعضاء الجدد في الفريق دمج SDK الدفع بمجرد إضافة تبعية واحدة—لم تعد هناك حاجة لتهيئة أي Beans يدوياً، وانخفض وقت التكامل من 3 أيام إلى 30 دقيقة.
3. آلية تحميل التهيئة التلقائية
(1) من @EnableAutoConfiguration إلى AutoConfiguration.imports
flowchart LR
A["@EnableAutoConfiguration"] --> B["استيراد<br/>AutoConfigurationImportSelector"]
B --> C["قراءة<br/>META-INF/spring/<br/>AutoConfiguration.imports"]
C --> D["تصفية عبر<br/>@Conditional<br/>التعليقات"]
D --> E["تسجيل<br/>أصناف التهيئة التلقائية<br/>المؤهلة"]
| الإصدار | ملف التحميل | التنسيق |
|---|---|---|
| Spring Boot 2.x | META-INF/spring.factories |
key=class1,class2 |
| Spring Boot 3.x | META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports |
اسم صنف مؤهل بالكامل في كل سطر |
AutoConfiguration.imports الجديد ولم يعد يستخدم spring.factories لتسجيل التهيئة التلقائية.
(2) طبيعة أصناف التهيئة التلقائية
صنف التهيئة التلقائية هو صنف @Configuration مع تعليقات شرطية:
(1) ▶ مثال: تبسيط الكود المصدري لتهيئة DataSource التلقائية
@AutoConfiguration
@ConditionalOnClass(DataSource.class)
@ConditionalOnMissingBean(DataSource.class)
@EnableConfigurationProperties(DataSourceProperties.class)
public class DataSourceAutoConfiguration {
@Bean
@ConfigurationProperties("spring.datasource")
public DataSource dataSource(DataSourceProperties properties) {
return DataSourceBuilder.create()
.url(properties.getUrl())
.username(properties.getUsername())
.password(properties.getPassword())
.build();
}
}
الناتج:
// التنفيذ ناجح
4. شرح مفصل للتعليقات الشرطية
(1) تعليقات الشرط الأساسية
| التعليق | الشرط | التطبيقات النموذجية |
|---|---|---|
@ConditionalOnClass |
الصنف المحدد موجود في مسار الأصناف | يسري فقط بعد تضمين التبعية |
@ConditionalOnMissingClass |
الصنف غير موجود في مسار الأصناف | توفير بديل عند غياب التبعية |
@ConditionalOnBean |
Bean محدد موجود في الحاوية | يُستخدم عند الاعتماد على Beans أخرى |
@ConditionalOnMissingBean |
Bean المحدد غير موجود في الحاوية | توفير Bean افتراضي؛ التنحي لتعريفات المستخدم عند توفرها |
@ConditionalOnProperty |
خصائص التهيئة تفي بالشروط | التحكم في الوظائف عبر مفاتيح التهيئة |
(1) ▶ مثال: التحكم بمفتاح @ConditionalOnProperty
@Configuration
@ConditionalOnProperty(
prefix = "orderflow.notification",
name = "enabled",
havingValue = "true",
matchIfMissing = false
)
public class NotificationConfig {
@Bean
public NotificationService emailNotificationService() {
return new EmailNotificationService();
}
}
الناتج:
// التنفيذ ناجح
orderflow:
notification:
enabled: true # اضبط false لتعطيل الإشعارات
(2) ▶ مثال: @ConditionalOnMissingBean يوفر تنفيذاً افتراضياً
@Configuration
public class OrderFlowAutoConfiguration {
@Bean
@ConditionalOnMissingBean(IdGenerator.class)
public IdGenerator uuidIdGenerator() {
return new UuidIdGenerator();
}
@Bean
@ConditionalOnMissingBean(OrderNumberGenerator.class)
@ConditionalOnProperty(
prefix = "orderflow.order",
name = "number-prefix",
havingValue = "ORD",
matchIfMissing = true
)
public OrderNumberGenerator defaultOrderNumberGenerator() {
return new SequentialOrderNumberGenerator("ORD");
}
}
الناتج:
// التنفيذ ناجح
5. Starter مخصص
(1) اصطلاحات تسمية Starter
| النوع | اصطلاح التسمية | مثال |
|---|---|---|
| Starter رسمي | spring-boot-starter-* |
spring-boot-starter-web |
| Starter طرف ثالث | *-spring-boot-starter |
orderflow-spring-boot-starter |
(2) هيكل مشروع Starter
orderflow-spring-boot-starter/
├── src/main/
│ ├── java/com/orderflow/autoconfigure/
│ │ ├── OrderFlowAutoConfiguration.java
│ │ └── OrderFlowProperties.java
│ └── resources/
│ └── META-INF/spring/
│ └── org.springframework.boot.autoconfigure.AutoConfiguration.imports
└── pom.xml
(1) ▶ مثال: الكود الكامل لـ Starter مخصص
// OrderFlowProperties.java
@ConfigurationProperties(prefix = "orderflow.notification")
public record OrderFlowNotificationProperties(
boolean enabled,
String fromEmail,
String templatePath
) {}
// OrderFlowAutoConfiguration.java
@AutoConfiguration
@ConditionalOnClass(JavaMailSender.class)
@ConditionalOnProperty(
prefix = "orderflow.notification",
name = "enabled",
havingValue = "true"
)
@EnableConfigurationProperties(OrderFlowNotificationProperties.class)
public class OrderFlowAutoConfiguration {
@Bean
@ConditionalOnMissingBean(NotificationService.class)
public NotificationService notificationService(
OrderFlowNotificationProperties props) {
return new EmailNotificationService(
props.fromEmail(),
props.templatePath()
);
}
}
الناتج:
التنفيذ ناجح
# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.orderflow.autoconfigure.OrderFlowAutoConfiguration
6. تصحيح أخطاء التهيئة التلقائية واستكشافها
(1) وضع --debug
عند إضافة معامل --debug عند التشغيل، يُخرج Spring Boot تقرير تهيئة تلقائية:
java -jar orderflow-service.jar --debug
(1) ▶ مثال: تفسير تقرير التهيئة التلقائية
============================
CONDITIONS EVALUATION REPORT
============================
Positive matches:
-----------------
DataSourceAutoConfiguration matched:
- @ConditionalOnClass found required class 'javax.sql.DataSource'
Negative matches:
-----------------
ActiveMQAutoConfiguration:
Did not match:
- @ConditionalOnClass did not find required class 'javax.jms.ConnectionFactory'
Exclusions:
-----------
None
Unconditional classes:
----------------------
org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration
الناتج:
التنفيذ ناجح
| قسم التقرير | المعنى |
|---|---|
| Positive matches | تهيئات تلقائية تفي بالشروط ونشطة |
| Negative matches | تهيئات تلقائية لا تفي بالشروط وغير سارية |
| Exclusions | تهيئات تلقائية مستبعدة صراحةً |
| Unconditional Classes | تهيئة تلقائية للتسجيل غير المشروط |
(2) استبعاد التهيئة التلقائية
(2) ▶ مثال: استبعاد التهيئات التلقائية غير المرغوب فيها
// الطريقة 1: الاستبعاد بالتعليق
@SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
HibernateJpaAutoConfiguration.class
})
public class OrderFlowApplication { ... }
// الطريقة 2: خاصية التهيئة
// application.yml
spring:
autoconfigure:
exclude:
- org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration
الناتج:
// التنفيذ ناجح
| طريقة الاستبعاد | السيناريوهات المناسبة | المرونة |
|---|---|---|
@SpringBootApplication(exclude) |
استبعاد دائم | محدد وقت الترجمة |
spring.autoconfigure.exclude |
استبعاد حسب البيئة | متغير وقت التشغيل |
@ConditionalOnProperty |
استبعاد حسب الشرط | الأكثر مرونة |
7. مثال شامل: التنفيذ الكامل لـ OrderFlow Notification Starter
// orderflow-notification-spring-boot-starter
// OrderFlowNotificationProperties.java
package com.orderflow.autoconfigure;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "orderflow.notification")
public record OrderFlowNotificationProperties(
boolean enabled,
String fromEmail,
String templatePath,
SmtpConfig smtp
) {
public record SmtpConfig(String host, int port, boolean ssl) {}
}
// NotificationService.java
package com.orderflow.autoconfigure;
public interface NotificationService {
void send(String to, String subject, String body);
}
// EmailNotificationService.java
package com.orderflow.autoconfigure;
public class EmailNotificationService implements NotificationService {
private final String fromEmail;
private final String templatePath;
public EmailNotificationService(String fromEmail, String templatePath) {
this.fromEmail = fromEmail;
this.templatePath = templatePath;
}
@Override
public void send(String to, String subject, String body) {
// منطق إرسال البريد الإلكتروني
System.out.printf("Send to %s: [%s] %s%n", to, subject, body);
}
}
// OrderFlowNotificationAutoConfiguration.java
package com.orderflow.autoconfigure;
import org.springframework.boot.autoconfigure.AutoConfiguration;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
@AutoConfiguration
@ConditionalOnClass(name = "org.springframework.mail.javamail.JavaMailSender")
@ConditionalOnProperty(prefix = "orderflow.notification", name = "enabled", havingValue = "true")
@EnableConfigurationProperties(OrderFlowNotificationProperties.class)
public class OrderFlowNotificationAutoConfiguration {
@Bean
@ConditionalOnMissingBean(NotificationService.class)
public NotificationService notificationService(OrderFlowNotificationProperties props) {
return new EmailNotificationService(props.fromEmail(), props.templatePath());
}
}
# META-INF/spring/org.springframework.boot.autoconfigure.AutoConfiguration.imports
com.orderflow.autoconfigure.OrderFlowNotificationAutoConfiguration
❓ أسئلة شائعة
📖 ملخص
- استخدام ملف
AutoConfiguration.importsلتسجيل أصناف التهيئة التلقائية في Spring Boot 3.x - جوهر صنف التهيئة التلقائية هو التعليقات الشرطية:
@ConditionalOnClass،@ConditionalOnMissingBean،@ConditionalOnProperty @ConditionalOnMissingBeanيُنفذ مبدأ "أسبقية تعريف المستخدم"- أسماء Starter المخصصة: رسمي
spring-boot-starter-*، طرف ثالث*-spring-boot-starter - يمكن عرض تقرير التهيئة التلقائية في وضع
--debugوعبر نقطة نهاية Actuator
📝 تمارين
-
تمرين أساسي (الصعوبة ⭐): شغّل مشروع OrderFlow باستخدام وضع
--debug، اسرد جميع أصناف التهيئة التلقائية ضمن "Positive matches"، وافهم شروط مسار الأصناف المطلوبة لكل تهيئة تلقائية. -
تمرين متقدم (الصعوبة: ⭐⭐): أنشئ
orderflow-spring-boot-starterيتضمن ميزة إشعارات تُتحكم بها بمفتاح@ConditionalOnProperty، ثم ادمجه في مشروع OrderFlow واختبره. -
تحدٍ (الصعوبة: ⭐⭐⭐): نفّذ نظام تهيئة تلقائية يدعم تطبيقات متعددة—استخدم إشعارات Kafka إذا كان Kafka موجوداً في مسار الأصناف، وإشعارات البريد الإلكتروني غير ذلك، وإشعارات السجل إذا لم يكن أي منهما متاحاً. فكّر في أولوية التعليقات الشرطية وتصميم الاستبعاد المتبادل.



