When reading about creating custom queries in Spring, I noticed that none of the classes (UserRepositoryCustom
, UserRepositoryCustomImpl
, UserRepository
) use the @Repository
annotation.
I was surprised by this, because usually all the Spring application classes are annotated by something for them to be detected and a proxy generated for them. That's how the aspect-oriented framework works in Java.
Then I checked my old working code, and realized that my repository interface also does not use the annotation. Yet, it is @Autowired
as a dependency into the controllers and other classes that use it. Example:
// AddressRepository.java
public interface AddressRepository extends CrudRepository<Address, String> {
}
// Repositories.java
@Getter // lombok
@Component
public class Repositories { // autowire this to have access to all repo's
private final AddressRepository addressRepository;
@Autowired
public Repositories(AddressRepository addressRepository) {
this.addressRepository = addressRepository;
}
}
This begs the questions: When should the annotation be used? and How come a non-annotated class is automatically detected by Spring's component scan?