Junior — Middle
Explain the purpose and usage of the @Repository annotation in Spring.
sobes.tech AI
Answer from AI
The @Repository annotation in Spring is used to designate a class as a component responsible for working with a database or other data storage mechanism.
Main purposes:
- Marks the class as a data access component so that Spring can automatically detect and register it in the application context.
- Allows Spring to handle database-related exceptions by translating them into unified Spring DataAccessException exceptions.
Example of usage:
@Repository
public class UserRepository {
// methods for working with the database
}
Thus, @Repository helps organize the data access layer and integrate it with the Spring infrastructure.