SONARJAVA-5289 Create rule S7179: @Cacheable and @CachePut should not be combined (#4612)

This commit is contained in:
github-actions[bot] 2025-01-27 11:49:43 +01:00 committed by GitHub
parent 11dd942825
commit 040c9dabef
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
3 changed files with 64 additions and 0 deletions

View File

@ -0,0 +1,24 @@
{
"title": "@Cacheable and @CachePut should not be combined",
"type": "CODE_SMELL",
"status": "ready",
"remediation": {
"func": "Constant\/Issue",
"constantCost": "5min"
},
"tags": [
"spring"
],
"defaultSeverity": "Major",
"ruleSpecification": "RSPEC-7179",
"sqKey": "S7179",
"scope": "Tests",
"defaultQualityProfiles": ["Sonar way"],
"quickfix": "unknown",
"code": {
"impacts": {
"RELIABILITY": "MEDIUM"
},
"attribute": "LOGICAL"
}
}

View File

@ -0,0 +1,38 @@
== Why is this an issue?
`@Cacheable` annotation is used to store the result of a method and avoid executing it for the same inputs.
`@CachePut` instead is used to force the execution of a method and store the result in the cache.
Annotating a method with both will produce unreliable behavior, except for specific corner-cases when their `condition()` or `unless()` expressions are mutually exclusive.
Hence this pattern is strongly discouraged and an issue will be raised on such cases.
== How to fix it
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
@Cacheable
@CachePut
void getBook(String isbn){ // Non compliant, methods annotated with both @Cacheable and @CachePut will not behave as intended
...
}
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
@Cacheable
void getBook(String isbn){
...
}
----
== Resources
=== Documentation
* Spring Documentation - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/CachePut.html[@CachePut]
* Spring Documentation - https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/cache/annotation/Cacheable.html[@Cacheable]

View File

@ -0,0 +1,2 @@
{
}