无法自动装配覆盖在父级中重写的方法的bean

时间:2016-06-30 12:06:14

标签: java spring spring-mvc inheritance

在我们的项目中,我们的结构与下面的代码类似。如果我取消注释指定的块,Spring将无法在PrintController中自动装配PrintService

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'PrintController': Injection of autowired dependencies failed; 
nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private printService; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [MyPrintService] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

为什么Spring有问题?

@Controller
public class PrintController {
   @Autowired
   private MyPrintService printService;
}

@Service
public class MyPrintService extends AbstractPrintService<MyModel> {
   /* uncomment this block to get error
   @Override
   public void print(MyModel model){
       //do stuff 
   }*/
}


public abstract class AbstractPrintService<M> extends CommonAbstractPrintService<M> {
}


public abstract class CommonAbstractPrintService<M> implements PrintService<M> {
   @Override
   public void print(M model){
       //do common stuff 
   }
}

public interface PrintService<M> {
   void print(M model);
}

解决方案是使用接口自动装配bean。所以而不是:

 @Autowired
 private MyPrintService printService;

我用过

@Autowired
private PrintService printService;

它突然起作用了。但我不知道为什么Spring被这种覆盖所冒犯了。如果有人能解释的话会很高兴的!谢谢!

0 个答案:

没有答案