网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

Noqualifyingbeanoftype问题解决-创新互联

No qualifying bean of type问题解决 前言

No qualifying bean of type ‘xxx.xxx.xxx’ available: expected single matching bean but found 2:xxx.xxx.xxx

创新互联建站总部坐落于成都市区,致力网站建设服务有成都网站建设、做网站、网络营销策划、网页设计、网站维护、公众号搭建、微信小程序开发、软件开发等为企业提供一整套的信息化建设解决方案。创造真正意义上的网站建设,为互联网品牌在互动行销领域创造价值而不懈努力!

对于一个java开发新手来说, 应该经常会遇到这个问题,而且还不好意思询问周围同事,不要怕,今天就让我们解决掉它。

问题及解决方案 问题1 包扫描不正确或未扫描
  • 默认情况下,如果使用了springboot,他会默认扫描启动类(使用了注解@SpringBootApplication)所在的包及子包,扫描的包中是否包含当前类所在的包。
  • 检查scanBasePackages扫描路径是否包含当前类所在的包。
解决方案
  • 将当前类所在的包加入扫描路径即可,例如当前类所在包为com.demo1

    @SpringBootApplication(@SpringBootApplication(scanBasePackages = {"com.demo","com.demo1"}))

    切记不要忘了扫描当前启动类所在的包 ,否则又会导致其他类不能注入。

问题2 当前类是否注入了spring环境
  • 当前类是否有 @Service @Component等注解
  • 当前类是否被@Bean初始化
解决方案
  • 增加对应注解将类注入到spring环境即可,例如:

    @Service
    public class ServiceImpl1 implements Service{}
    或
    @Component
    public class ServiceImpl1 implements Service{}
    或
    @Bean
    public ServiceImpl serviceImpl(){return new ServiceImpl();
    }

    使用@Bean方法所在的类也必须是要注入到spring环境中的。

问题3 多个类实现了同一个接口
  • 查看当前接口是否被多个类实现

  • 多个实现类是否未设置BeanName或者设置了相同的BeanName,例如:

    @Service
    public class ServiceImpl1 implements Service{}
    @Service
    public class ServiceImpl2 implements Service{}
    或
    @Service("Service1")
    public class ServiceImpl3 implements Service{}
    @Service("Service1")
    public class ServiceImpl4 implements Service{}

    以上方式都会出现异常。

  • 注入Bean时是否指定了设置的BeanName,例如:

    @Autowired
     private Service service;
解决方案

当我们需要多个类实现同一个接口时,需要为每个实现类配置BeanName,例如:

@Service("serviceImpl3")
public class ServiceImpl3 implements Service{}
@Service("serviceImpl2")
public class ServiceImpl2 implements Service{}
@Service("serviceImpl1")
public class ServiceImpl1 implements Service{}

建议首字母小写。

以上没有问题,那么使用的时候还需要指定BeanName,例如:

@Qualifier(value = "serviceImpl1")
@Autowired
private Service service;

关于@Qualifier使用,详见:Spring @Qualifier 注释

如果不想在每个使用处设置@Qualifier,只想在特殊场景下设置,那么只需要在默认的实现类上增加注解@Primary,例如:

@Primary
@Service
public class ServiceImpl implements Service{}

那么在使用的时候就可以直接注入了,默认会使用ServiceImpl,例如:

@Autowired
private Service service;
注意事项

当存在多个相同类型的Bean,强烈建议使用@Primary把其中某一个Bean标识为“主要的”,使用@Autowired注入时会首先使用被标记为@Primary的Bean。

你是否还在寻找稳定的海外服务器提供商?创新互联www.cdcxhl.cn海外机房具备T级流量清洗系统配攻击溯源,准确流量调度确保服务器高可用性,企业级服务器适合批量采购,新人活动首月15元起,快前往官网查看详情吧


分享标题:Noqualifyingbeanoftype问题解决-创新互联
标题URL:http://bjjierui.cn/article/djpsig.html

其他资讯