首页 > 开发 > JAVA > 正文

spring in action中第五章 接口注入 提示没有找到bean,而在第二章中能够注入接口,有什么区别

2017-09-07 08:33:43  来源:网友分享

第二章

  1. CompacDisc接口

    package soundsystem;    public interface CompactDisc {        void play();    }
  1. CDPlayer

package soundsystem;        import org.springframework.beans.factory.annotation.Autowired;        import org.springframework.stereotype.Component;                @Component        public class CDPlayer  {                  private CompactDisc cd;                      //这里能够Autowired             @Autowired          public CDPlayer(CompactDisc cd) {            this.cd = cd;          }                  public void play() {            cd.play();          }        }

第五章

  1. SpittleRepository接口

      package spittr.data;                import spittr.Spittle;                import java.util.List;                        public interface SpittleRepository {            List<Spittle> findSpittles(long max, int count);        }  
  1. SpittleController

package spittr.web;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.ui.Model;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import spittr.data.SpittleRepository;@Controller@RequestMapping("/spittles")public class SpittleController {    private SpittleRepository spittleRepository;    //这里提示无法autowired    @Autowired    public SpittleController(SpittleRepository spittleRepository){        this.spittleRepository = spittleRepository;    }    @RequestMapping(method = RequestMethod.GET)    public String spittles(Model model){        spittleRepository.findSpittles(Long.MAX_VALUE,20);        return "spittles";    }}

和第二章有什么区别?
错误提示
Error creating bean with name 'spittleController' defined in file [C:UserschenIdeaProjectsspringactionoutartifactsspringaction_war_explodedWEB-INFclassesspittrwebSpittleController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'spittr.data.SpittleRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {}
显示没有定义这个bean,再对接口进行实现就能够去掉错误,为什么第二章却能够不对接口进行实现?

解决方案

唯一能想到的是你的CDPlayer没有被spirng容器初始化,我知道@Lazy可以做到,可你没有加,你自己查看一下配置,从lazy-init的角度考虑一下(可以给CDPlayer添加一个有打印日志的构造方法来校验问题)