I'm try to replace some java code with kotlin.
Such as jpa or cache.
The Start class is:
@EnableAsync
@EnableCaching
@EnableSwagger2
@SpringBootApplication
open class Application
fun main(args: Array<String>) {
SpringApplication.run(Application::class.java)
}
The simple controller:
@RestController
class CacheController {
@Autowired
private lateinit var cache: CacheService
@PutMapping("{id}")
fun save(@PathVariable id: Long) {
cache.save(id)
}
}
CacheService:
@Component
@CacheConfig(cacheNames = arrayOf("longCacheManager"), cacheManager = "longCacheManager")
open class CacheService {
@Cacheable(key = "#id")
fun save(id: Long): Long {
return id
}
}
cacheManager:
@Configuration
open class CacheConfig {
@Autowired
private lateinit var redisConnectionFactory: RedisConnectionFactory
@Bean
@Qualifier("longCacheManager")
open fun longCacheManager(): CacheManager {
val redisTemplate = StringRedisTemplate(redisConnectionFactory)
redisTemplate.valueSerializer = GenericToStringSerializer(Long::class.java)
val cacheManager = RedisCacheManager(redisTemplate)
cacheManager.setUsePrefix(true)
return cacheManager
}
}
I can confirm the parameter of id entered in CacheService's method save, but after I have excute the PutMethod, there is nothing in redis.
When I write the cacheServie with java like this, the redis would be save what I want.
The Java cache service like this:
@Component
@CacheConfig(cacheNames = "longCacheManager", cacheManager = "longCacheManager")
public class JavaCacheService {
@Cacheable(key = "#id")
public Long save(Long id) {
return id;
}
}
I have also read some article like this: https://pathtogeek.com/spring-boot-caching-with-kotlin
My SpringBootVersion is 1.5.3.RELEASE
and kotlinVersion is 1.1.3-2
Thanks all, I have fix it by make the cache method open
@Component
@CacheConfig(cacheNames = arrayOf("longCacheManager"), cacheManager = "longCacheManager")
open class CacheService {
@Cacheable(key = "#id.toString()")
open fun save(id: Long): Long {
return id
}
}
Spring generated proxy with cglib.
It must mandatory inherit the classes and methods.
But kotlin default is final class and method which without the keyword open.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With