पाठ 29 / 38
Spring Boot, Spring Data JPA व Annotation
'hello world' से आगे Spring Boot — starter व auto-configuration, Spring Data JPA से repository इंटरफ़ेस, और मुख्य stereotype व वायरिंग annotation।
Starter व auto-configuration
Starter (spring-boot-starter-web आदि) चुनी हुई डिपेंडेंसी का बंडल है। Auto-configuration classpath देखकर मेल खाते bean कॉन्फ़िगर करता है — ज़रूरत पर ही application.properties में override करें।
Spring Data JPA: मुफ़्त में repository
JpaRepository<Entity, IdType> एक्सटेंड करें और save, findById, findAll, delete मुफ़्त में मिलें। नामकरण परंपरा के अनुसार मेथड घोषित करें और Spring मेथड नाम से क्वेरी निकाल लेता है — कोई SQL या implementation नहीं।
interface OrderRepository extends JpaRepository<Order, Long> {
List<Order> findByStatusAndCustomerId(Status status, Long customerId);
Optional<Order> findFirstByCustomerIdOrderByCreatedAtDesc(Long customerId);
}मुख्य annotation
@Component किसी भी Spring-प्रबंधित bean को चिह्नित करता है; @Service व @Repository इसके अर्थपूर्ण विशेषीकरण हैं। @Autowired इंजेक्शन का अनुरोध करता है (एकल कंस्ट्रक्टर पर वैकल्पिक)। @RestController = @Controller + @ResponseBody, यानी हर मेथड का रिटर्न मान सीधे JSON के रूप में लिखा जाता है।