2017-05-09 175 views
1

无法注入的基类直接无法注入基类@Inject注解

抽象基类

@Component 
public abstract class A{ 
} 

Here are my derived classes 
@Named("abc") 
public class B extends A{ 
} 

@Named("cde") 
public class C extends A{ 
} 

我试图调用一个在我的资源类,但得到以下错误。

org.springframework.beans.factory.UnsatisfiedDependencyException:应用程序的启动过程中

@Inject 
private A a 

@Component 
public class Resource implements ServiceImpl{ 
@Inject 
    public Resource(final Client client, 
      final A a) { 
     Assert.notNull(client); 
     Assert.notNull(a); 

     this.client = client; 
     this.a= a; 

    } 

    @Override 
    public Response method1(final Request request) { 
     Response response = null; 
     try { 
       response = (PaymentResponse) this.a.process(request); 
      } 
      catch (final Exception ex) { 
       ex.printstackTrace(); 
      } 


      return response; 
     } 
    } 

    @Override 
    public Response method2(final Request request) { 
     Response response = null; 
     try { 
      response = this.a.process(request); 
     } 
     catch (final Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
     return response; 

    } 
} 

错误错误创建名称为豆 '资源' 文件 类型的没有合格的bean定义的 'A'被定义为:期望单个匹配bean但发现2:b,c

回答

0

要注入正确的bean,您必须使用@Qualifier注释。

@Inject @Qualifier("abc") 
private A a; 

现在Spring不知道你要注入什么bean。 'abc'或'cde'。

由于您的基类是抽象的,因此您无法创建它的实例,因此spring正在尝试注入derieved类。这就是为什么你必须通过正确注释来决定哪些类需要注入。

+0

是否有替代方法。因为我试图将相同的基类扩展到30个不同的类。所以要避免同样的注射30次? 。还有一种方法可以在方法级别使用限定符? – dev21

+0

如果它不一定是组件,您可以创建工厂组件并将其注入其他组件。工厂可以创建你的基类中预期的对象。我不确定你想要达到的目标,但是创建30个课程可能是不好的设计的标志,你可能想重新思考你的解决方案。如果我帮忙,请接受我的回答。 –