Luis Fernandez
Luis Fernandez

Reputation: 559

Why is the @Repository annotation necesssary on a JpaRepository?

I have the following repository:

import org.springframework.data.jpa.repository.JpaRepository;

public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
    Employee findByName(String name);
}

Assume Employee is your usual entity class with id, name and surname.

I wire this class to my EmployeeService and use it like this:

@Service
public class EmployeeService {

    @Autowired
    private EmployeeRepository repository;

    public Employee saveEmployee(Employee employee) {
        return repository.save(employee);
    }
}

Would it make any difference to add the @Repository annotation to the repository?

Example:

import org.springframework.data.jpa.repository.JpaRepository;

@Repository
public interface EmployeeRepository extends JpaRepository<Employee, Integer> {
    Employee findByName(String name);
}

Upvotes: 2

Views: 1134

Answers (1)

crizzis
crizzis

Reputation: 10716

The @Repository annotation is not required on Spring Data repositories. Spring Boot detects repository beans based on the fact that they extend the Repository interface.

In fact, you need to suppress this behavior using @NoRepositoryBean if you want the repository bean to not be created.

The @Repository annotation is a specialization of @Component. If you were implementing repositories without the help of Spring Data, you could annotate them with @Repository to declare them as beans as well as hint at their role in your app.

Upvotes: 7

Related Questions