About @Resource injected into different types

Such as:

@Resource(name = "redisTemplate")
private HashOperations  hash;

redisTemplate not HashOperations implementation class, two classes in the inheritance did not have any relationship.

The reason is that a portion doGetBean () code

 // Check if required type matches the type of the actual bean instance.
if (requiredType != null && bean != null && !requiredType.isInstance(bean)) {
    try {
        return getTypeConverter().convertIfNecessary(bean, requiredType);
    }
    catch (TypeMismatchException ex) {
        if (logger.isDebugEnabled()) {
            logger.debug("Failed to convert bean '" + name + "' to required type '" +
                    ClassUtils.getQualifiedName(requiredType) + "'", ex);
        }
        throw new BeanNotOfRequiredTypeException(name, requiredType, bean.getClass());
    }
}

If the target object and the reference object is not of the same type, that is, as redisTemplate and HashOperations no inheritance or interface implementations relationship, then spring will be converted with the editor.

String editorName = targetType.getName() + "Editor";
        try {
            Class<?> editorClass = cl.loadClass(editorName);
            if (!PropertyEditor.class.isAssignableFrom(editorClass)) {
                if (logger.isWarnEnabled()) {
                    logger.warn("Editor class [" + editorName +
                            "] does not implement [java.beans.PropertyEditor] interface");
                }
                unknownEditorTypes.add(targetType);
                return null;
            }
            return (PropertyEditor) instantiateClass(editorClass);
        }

spring will be to load HashOperations + Editor, that is loaded HashOperationsEditor this class. And such must inherit PropertyEditorSupport or implement PropertyEditor interface.

Here Insert Picture Description

This class is very simple, it overrides setValue method, RedisOperations in opsForHash () returns the value set in, and opsForHash () return value is the DefaultHashOperations.

Here Insert Picture Description
Here Insert Picture DescriptionHere Insert Picture DescriptionSo that we get value with the editor when you can get to the DefaultHashOperations. It can be injected into HashOperations DefaultHashOperations go.

Published 97 original articles · won praise 44 · Views 300,000 +

Guess you like

Origin blog.csdn.net/wangh92/article/details/102946856