Reputation: 337
I am trying to understand which types of beans in Spring are being proxied, so far i understood its the @Aspect
, @Transactional
annotated classes. So I played a bit on my PC, and noted that if I annotate a class with @Component
, it's not getting proxied when Autowired, but if I just change the annotation to @Repository
, it is proxied by CGLIB. As far as i understand, @Repository
is just an alias of @Component
, why is it getting proxied and the other one not ?
Here are the example very simple classes
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
@Repository
public class JustForTest {
private final String hello = "";
public String getHello() {
return hello;
}
}
and
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Repository;
@Component
public class JustForTest {
private final String hello = "";
public String getHello() {
return hello;
}
}
Upvotes: 0
Views: 196
Reputation: 5284
Why does Spring need to proxy bean classes? The basic high level answer is: because it needs to add additional logic to the class at runtime so you don't have to write it yourself (or configure things in lengthy XML descriptor files...). Just like the @Transactional
annotation adds magic transaction management to bean methods, the Repository annotation must also have something attached to it; you know this for a fact already because the bean gets proxied as soon as you add the annotation.
So to find your answer, simply research what the purpose of the Repository annotation is. A basic search brings up this article from a reputable source which exactly puts it as simple as I was hoping to be able to put it:
https://www.baeldung.com/spring-component-repository-service
I quote:
@Repository’s job is to catch persistence-specific exceptions and re-throw them as one of Spring’s unified unchecked exceptions
Read: this functionality is added at runtime. Hence: proxy.
Upvotes: 3