What annotation is used to inject a Spring Data JPA repository into a service or controller?
4 phương ánCó giải thíchDễ
Các phương án trả lời
Chọn một phương ánLời giảiChọn phương án để mở
Để inject một Spring Data JPA repository vào một service hoặc controller, chúng ta sử dụng annotation @Autowired. Annotation này cho phép Spring tự động inject các bean vào các field hoặc setter của class. Điều này giúp giảm thiểu sự phức tạp khi viết mã và tăng cường tính tái sử dụng của code. Ví dụ, nếu chúng ta có một interface được tạo bởi Spring Data JPA, như sau:
public interface UserRepository extends JpaRepository<User, Long> {
}Thì chúng ta có thể inject nó vào một service như sau: @Service
public class UserService {
@Autowired private UserRepository userRepository;
}Trong ví dụ trên, Spring sẽ tự động inject UserRepository vào UserService.