无法通过限定符注入

时间:2018-06-12 07:19:04

标签: java spring proxy

我有一个名为Retry的自定义注释,后面是Bean Post Processor:

@Component
public final class RetryBPP implements BeanPostProcessor {

    private final Map<String, ClassDefinition> map = new HashMap<>(40);

    @Override
    public Object postProcessBeforeInitialization(final Object bean, final String beanName) throws BeansException {
        final Class<?> asClass = bean.getClass();
        final Method[] methods = asClass.getMethods();
        final List<Method> collect = Stream.of(methods)
                .filter(method -> method.isAnnotationPresent(Retriable.class))
                .collect(Collectors.toList());
        if(!collect.isEmpty()){
            this.map.put(beanName,new ClassDefinition(collect,asClass));
        }
        return bean;
    }

    @Override
    public Object postProcessAfterInitialization(final Object bean, final String beanName) throws BeansException {
        final ClassDefinition definition = this.map.get(beanName);
        if(definition != null){
            final Class beanClass = definition.baseCLass;
            return Proxy.newProxyInstance(beanClass.getClassLoader(), beanClass.getInterfaces(), (proxy, method, args) -> {
                if(definition.isMethodPresent(method)){
                    return this.retry(definition.originalMethod(method),bean,args);
                } else{
                    return method.invoke(bean,args);
                }
            });
        } else{
            return bean;
        }
    }

    private Object retry(final Method method,final Object originalBean,Object[] argc){
        final Retriable retriable = method.getAnnotation(Retriable.class);
        int attempts = retriable.attempts();
        while(true){
            try{
                return method.invoke(originalBean,argc);
            }catch (final Exception throwable){
                if(this.support(retriable.exceptions(),throwable.getClass()) && attempts != 0){
                    attempts--;
                    log.warn("Error on method {} wait to repeat",method.getName());
                    this.sleep(retriable.delay(),retriable.timeUnit());
                } else{
                    throw new RuntimeException(throwable);
                }
            }
        }
    }

    @SneakyThrows(InterruptedException.class)
    private void sleep(final long time, final TimeUnit timeUnit){
        timeUnit.sleep(time);
    }

    private boolean support(final Class<? extends Exception>[] exceptions,Class<? extends Exception> exception){
        boolean support = false;
        for (Class _class : exceptions) {
            if(_class.equals(exception)){
                support = true;
                break;
            }
        }
        return support;
    }

    @AllArgsConstructor
    private static final class ClassDefinition{
        final List<Method> methods;
        final Class baseCLass;

        boolean isMethodPresent(final Method method){
            return this.methods.stream()
                               .anyMatch(mthd->methodEquals(mthd,method));
        }

        Method originalMethod(final Method method){
            return this.methods.stream()
                               .filter(mthd->methodEquals(mthd,method))
                               .findFirst().orElseThrow(NullPointerException::new);

        }

    }

}

接口:

public interface Inter {

    String qqq(String url);

}

抽象类:

public abstract class Abs implements Inter {

    @Override
    @Retry
    public String qqq(final String url) {
        someLogic(url);
    }

  protected String someLogic(String str);

自定义限定符注释:

@Retention(RetentionPolicy.RUNTIME)
@Qualifier
@Target({ElementType.CONSTRUCTOR, ElementType.TYPE, ElementType.PARAMETER, ElementType.FIELD})
public @interface Qualif {

    VV.v type();

}

并实施:

@Service
@Qualif(type = First)
@Slf4j
public final class Impl extends Abs {

   @Override
   protected String someLogic(String str){...}
}

当我通过这样的限定符自动装配时:

@Autowired
@Qualif(type = First)
Inter inter;

Spring throw exception No qualifying bean of type [com.devadmin.downloader.sites.VideoDownloader] found for dependency Inter :,但是当我从abctract类中删除@Retry注释时,一切都很酷。如何解决这个问题。

BTW我检查了我的类在ApplicationContext内扩展Abstract类但是Spring没有看到我的自定义限定符

1 个答案:

答案 0 :(得分:0)

最后我找到了答案。对于那些不了解问题的人。

我有方法foo()抽象类的接口,它实现了这个接口,并添加了新的抽象方法,如

abstract class FooAbs impl Inter{
   @Override 
   void foo(){
      childMethod();
    }
   protected void childMethod();
}

最后,我使用@Component扩展Abstract类。

@Component 
class Trst extends FooAbs{

  @Override
  void childMethod(){}
}

问题在于动态代理。

以下代码

Proxy.newProxyInstance(beanClass.getClassLoader(), beanClass.getInterfaces(), (proxy, method, args) -> {}

动态代理不会看到getInterfaces因此我将我的班级签名更改为:

@Component 
    class Trst extends FooAbs implement Inter{

      @Override
      void childMethod(){}
    }

在此步骤之后

beanClass.getInterfaces()

参见Inter界面。我知道它解决了解决方案,我将重写我的代码以避免这种结构。但它有用,也许对某些人来说会有所帮助