I am new to Spring and read that we can't use @Cacheable
with static method
but can't found why we can't use so any one can explain so that beginner can understood easily? Can we use static method for retrieving database table
? I have made static method
of all method of service layer
of DAO so Is this thread-safe
?
Elaborating on my comment:
"Static methods cannot be cached. The way aspects work in Spring is by adding a wrapper class (a proxy) to the annotated class. There is no way in Java to add a wrapper to a static method."
Since Spring needs an object to wrap around in order to intercept calls to that object and perform various operations before delegating the modified input to the original object (thus spring aspects are possible).
Since anything that is static
cannot be instantiated as an object, Spring has no way to wrap around it and intercept its calls (at least with the current implementation of Spring)
It is a limitation of the mechanism used to provide caching.
When you mark some method as @Cacheable
, Spring creates a proxy to your bean that intercepts method invocations and provides the caching, and will inject that instead of the original bean. So if you have some code like:
@Inject
private MyBean myBean;
...
myBean.myMethod("foo");
where MyBean
has declared myMethod()
as @Cacheable
, then myBean
will not point to what you put in the application context, but to a proxy that will do the caching and invoke the original MyBean.myMethod()
only when cache lookup does not return anything.
Proxys cannot intercept static methods, so the proxy cannot cache static methods. That is why @Cacheable
will not work on static methods.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.