我在创建Spring CacheManager时遇到了困难。当我试图引导时,我会得到一个创建bean消息的错误。
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.concurrent.ConcurrentMapCacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@EnableCaching
@Configuration
public class CacheConfig {
@Bean
public CacheManager cacheManager() {
log.trace("Creating cache manager.");
return new ConcurrentMapCacheManager("myCache");
}
}我已经在日志行上放置了一个调试标记,但是我没有到达。在我们找到这个方法之前,似乎发生了一些事情。
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:132)
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:124)
at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:190)
at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:132)
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:244)
at org.springframework.test.context.junit.jupiter.SpringExtension.postProcessTestInstance(SpringExtension.java:138)
at org.junit.jupiter.engine.descriptor.ClassBasedTestDescriptor.lambda$invokeTestInstancePostProcessors$6(ClassBasedTestDescriptor.java:350)
...
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'cacheManager' defined in class path resource [org/chuck/config/CacheConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.cache.CacheManager]: Illegal arguments to factory method 'cacheManager'; args: ; nested exception is java.lang.IllegalArgumentException: object is not an instance of declaring class解决方案(多亏奈杰尔·萨维奇)
不要将类命名为CacheConfig
发布于 2022-07-09 10:15:41
对于spring类/bean扫描,名称空间有一堆缓存annotations1。
在这里,他们创建了自己的配置bean/类来缓存CacheConfig,这是一个典型的名称,具有类名CacheConfig。
这里的问题是Spring开发人员有一个annotation1 @CacheConfig,它还有一个类名CacheConfig。
从错误中可以看出,Spring上下文试图通过一个org.springframework.cache.annotation.CacheConfig类的BeanFactory来实现org.chuck.config.CacheConfig.class,该类的工厂方法引用了org.chuck.config.CacheConfig.class类(在本例中是接口)。
我认为只有当工厂没有使用完全限定的类名时才会发生这种情况,我能很快找到的唯一证据就是来自这个issue3的评论。
简单的解决方案就是重命名它们自己的配置bean/类
2您应该了解CDI如何使用代理类和范围启发式来创建对象,代理是在运行时创建的bean的子类,我们可以在错误消息object is not an instance of declaring class中得到这方面的提示。
https://docs.spring.io/spring-javaconfig/docs/1.0.0.m3/reference/html/creating-bean-definitions.html
“当然,您可以为扫描指定一个自定义的BeanNameGenerator,并使用更独特的bean名称,例如完全限定的类名。”
https://stackoverflow.com/questions/68959734
复制相似问题