在SpringBoot中注⼊RedisTemplate实例异常的解决⽅案
⽬录
注⼊RedisTemplate实例异常
贴出详细的错误⽇志
最后想再验证⼀个⼩的问题
注⼊RedisTemplate实例异常
最近,在项⽬开发过程中使⽤了RedisTemplate,进⾏单元测试时提⽰
Field redisTemplate ample.demo1.dao.RedisDao required a bean of type ‘org.RedisTemplate’ that could not be found
翻译过来就是“不到类型为RedisTemplate的bean”。
当然,仅看这句话我们⽆法确定为什么会出现这个问题。
贴出详细的错误⽇志
2018-08-10 14:53:49.761 - Caught exception while allowing TestExecutionListener [st.context.web.ServletTestExecutionListener@5af3afd9] to prepare test instance [ample.demo1.Demo1ApplicationTests@2361365c]
java.lang.IllegalStateException: Failed to load ApplicationContext
at st.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:124)
at st.context.ApplicationContext(DefaultTestContext.java:83)
at st.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:189)
at st.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:131)
at st.context.TestContextManager.prepareTestInstance(TestContextManager.java:230)
at st.context.ateTest(SpringJUnit4ClassRunner.java:228)
at st.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:287)
at org.junit.del.ReflectiveCallable.run(ReflectiveCallable.java:12)
at st.context.hodBlock(SpringJUnit4ClassRunner.java:289)
at st.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:247)
at st.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at st.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at st.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at st.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
lipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
lipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
lipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
lipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
lipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
lipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'redisDao': Unsatisfied dependency expressed through field 'redisTemplate'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'org.RedisTemplate<java.lang.String, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1264)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:553)
at org.springframework.beans.factory.ateBean(AbstractAutowireCapableBeanFactory.java:483)
at org.springframework.beans.factory.support.Object(AbstractBeanFactory.java:306)
at org.springframework.beans.factory.Singleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302)
at org.springframework.beans.factory.Bean(AbstractBeanFactory.java:197)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761)
at t.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867)
at t.fresh(AbstractApplicationContext.java:543)
at org.springframework.fresh(SpringApplication.java:693)
at org.springframework.freshContext(SpringApplication.java:360)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:303)
at org.st.context.SpringBootContextLoader.loadContext(SpringBootContextLoader.java:120)
at st.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContextInternal(DefaultCacheAwareContextLoaderDelegate.java:98) at st.context.cache.DefaultCacheAwareContextLoaderDelegate.loadContext(DefaultCacheAwareContextLoaderDelegate.java:116)
... 25 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type
'org.RedisTemplate<java.lang.String, java.lang.Object>' available: expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1493)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1104)
at org.springframework.beans.factory.solveDependency(DefaultListableBeanFactory.java:1066)
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:585) ... 43 common frames omitted
看到这⼀⼤段错误⽇志是不是有点晕,其实我们只需要看关键的错误⽇志就可以定位到问题。
错误⽇志中的第⼆个Caused by打印了关键的错误⽇志:
No qualifying bean of type ‘org.RedisTemplate< java.lang.String, java.lang.Object>
笔主回看写的代码,在注⼊RedisTemplate< K, V>时指定了具体的类型。
@Component
public class RedisDao {
/**
* 注⼊时指定了K、V类型
*/
@Autowired
private RedisTemplate<String, Object> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Resource(name="redisTemplate")
ValueOperations<String, Object> valOpsObj;
@Resource(name="stringRedisTemplate")
ValueOperations<String, String> valOpsStr;
}
根据错误⽇志查看DefaultListableBeanFactory这个类的第1493⾏的代码,源码如下:
/**
* 为⽆法解决的依赖抛出NoSuchBeanDefinitionException或BeanNotOfRequiredTypeException。
* Raise a NoSuchBeanDefinitionException or BeanNotOfRequiredTypeException
* for an unresolvable dependency.
*/
private void raiseNoMatchingBeanFound(
Class<?> type, ResolvableType resolvableType, DependencyDescriptor descriptor) throws BeansException {
checkBeanNotOfRequiredType(type, descriptor);
//抛出NoSuchBeanDefinitionException
throw new NoSuchBeanDefinitionException(resolvableType,
"expected at least 1 bean which qualifies as autowire candidate. " +
"Dependency annotations: " + ObjectUtils.Annotations()));
}
/**
* 为⽆法解决的依赖抛出BeanNotOfRequiredTypeException,如果适⽤,例如,bean的⽬标类型匹配但是公开的代理不匹配。
*
*
* Raise a BeanNotOfRequiredTypeException for an unresolvable dependency, if applicable,
* i.e. if the target type of the bean would match but an exposed proxy doesn't.
springframework和springboot
*/
private void checkBeanNotOfRequiredType(Class<?> type, DependencyDescriptor descriptor) {
for (String beanName : this.beanDefinitionNames) {
RootBeanDefinition mbd = getMergedLocalBeanDefinition(beanName);
Class<?> targetType = TargetType();
if (targetType != null && type.isAssignableFrom(targetType) &&
isAutowireCandidate(beanName, mbd, descriptor, getAutowireCandidateResolver())) {
// Probably a proxy interfering with target type match -> throw meaningful exception.
Object beanInstance = getSingleton(beanName, false);
Class<?> beanType = (beanInstance != null ? Class() : predictBeanType(beanName, mbd));
if (!type.isAssignableFrom((beanType))) {
//抛出BeanNotOfRequiredTypeException
throw new BeanNotOfRequiredTypeException(beanName, type, beanType);
}
}
}
BeanFactory parent = getParentBeanFactory();
if (parent instanceof DefaultListableBeanFactory) {
((DefaultListableBeanFactory) parent).checkBeanNotOfRequiredType(type, descriptor);
}
}
这两个⽅法说明了没有到RedisTemplate< String, Object>可以匹配的Bean,那么这个问题该如何解决呢?不妨在使⽤RedisTemplate< K, V>时不指定具体的类型,修改代码如下:
/**
* 注⼊时不指定K、V的类型
*/
@Autowired
private RedisTemplate redisTemplate;
重新启动服务,启动⽇志没有报错,RedisTemplate注⼊Bean成功了。
为什么RedisTemplate< String, Object>注⼊Bean会失败呢,很是纳闷。思考很久,想到RedisTemplate在SpringBoot框架中是⾃动配置的,容器中默认的就是RedisTemplate 的实例。
想到这⾥,就需要翻下官⽹的⽂档,看看官⽹⽂档有没有什么说明。果然,官⽅⽂档第30.1.1章节还是针对RedisTemplate做了说明。
If you add your own @Bean of any of the auto-configured types, it replaces the default (except in the case of RedisTemplate, when the exclusion is based on the bean name, redisTemplate, not its type).
如果针对⾃动配置类型添加⾃⼰的Bean,它将取代默认的。我的代码好像写的没问题啊,等等…括号中这句话才是重点啊。翻译⼀波,在RedisTemplate的情况下除外,当排除基于Bean的名称,⽽不是它的类型。英⽂不太好,怎么翻译好像都不⼤通顺。
现在好像明⽩了,刚才的RedisTemplate< String, Object>注⼊时⽤到了@Autowired,@Autowired默认按照类型装配的。也就是说,想要获取RedisTemplate< String, Object>的Bean,要根据名字装配。那么⾃然想到使⽤@Resource,它默认按照名字装配。
再次修改代码如下:
/**
* 注⼊时指定了K、V类型
*/
@Resource
private RedisTemplate<String, Object> redisTemplate;
再次重新启动服务,启动⽇志没有报错,RedisTemplate< String, Object>注⼊Bean成功了。通过这个错误,学习到SpringBoot框架中⾃动配置类的⼀个特性。同时,也反映出学习⼀门技术要从官⽹开始,避免踩坑。
在实际开发过程中,使⽤RedisTemplate< K, V>不是必须指定K、V的类型,使⽤默认的Bean就能满⾜需求。
最后想再验证⼀个⼩的问题
再次修改代码如下:
/**
* Redis访问⼯具类
* @author zhaoheng
* @date 2018年8⽉10⽇
*/
@Component
public class RedisDao {
/**
* 注⼊时指定K、V类型都为String
*/
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Autowired
private StringRedisTemplate stringRedisTemplate;
/**
* ⽐较两个对象是否是同⼀个对象
*/
public boolean compare () {
LOG.info("redisTemplate的hashcode:{}", redisTemplate.hashCode());
LOG.info("stringRedisTemplate的hashcode:{}", stringRedisTemplate.hashCode());
LOG.info("equal()的结果:{}", redisTemplate.equals(stringRedisTemplate));
return redisTemplate == stringRedisTemplate;
}
}
/**
* 单元测试类
* @author zhaoheng
* @date 2018年8⽉10⽇
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class Demo1ApplicationTests {
private static final Logger LOG = Logger(Demo1ApplicationTests.class);
@Autowired
private RedisDao redisDao;
@Test
public void contextLoads() {
boolean flag = redisDaopare();
LOG.info("redisTemplate和stringRedisTemplate的⽐较结果:{}", flag);
}
}
上边这段代码在注⼊RedisTemplate时指定K、V都为String类型,在compare()⽅法中⽐较redisTemplate和stringRedisTemplate是否是同⼀个对象。运⾏下单元测试类,测试结果如下:
2018-08-10 18:30:57.075 - Started Demo1ApplicationTests in 15.58 seconds (JVM running for 16.974)
2018-08-10 18:30:57.360 - redisTemplate的hashcode:1996087296
2018-08-10 18:30:57.360 - stringRedisTemplate的hashcode:1996087296
2018-08-10 18:30:57.363 - equal()的结果:true
2018-08-10 18:30:57.364 - redisTemplate和stringRedisTemplate的⽐较结果:true
测试结果表明redisTemplate和stringRedisTemplate是同⼀个对象。等等…这次注⼊RedisTemplate时指定K、V都为String为什么没有错呢?⽽且,两个对象竟然是同⼀个对象。还是来看下StringRedisTempla
te的源码吧。
public class StringRedisTemplate extends RedisTemplate<String, String> {
/**
* Constructs a new <code>StringRedisTemplate</code> instance. {@link #setConnectionFactory(RedisConnectionFactory)}
* and {@link #afterPropertiesSet()} still need to be called.
*/
public StringRedisTemplate() {
RedisSerializer<String> stringSerializer = new StringRedisSerializer();
setKeySerializer(stringSerializer);
setValueSerializer(stringSerializer);
setHashKeySerializer(stringSerializer);
setHashValueSerializer(stringSerializer);
}
/**
* Constructs a new <code>StringRedisTemplate</code> instance ready to be used.
*
* @param connectionFactory connection factory for creating new connections
*/
public StringRedisTemplate(RedisConnectionFactory connectionFactory) {
this();
setConnectionFactory(connectionFactory);
afterPropertiesSet();
}
protected RedisConnection preProcessConnection(RedisConnection connection, boolean existingConnection) {
return new DefaultStringRedisConnection(connection);
}
}
看了源码是不是理解了,因为StringRedisTemplate类的⽗类就是RedisTemplate< String, String>,⽽Bean默认是单例的,两个是⾃然是同⼀个对象了。
以上为个⼈经验,希望能给⼤家⼀个参考,也希望⼤家多多⽀持。
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论