springboot自动注入避坑

简介: springboot自动注入避坑

一、required a single bean, but 2 were found

原因:自动注入需要一个,系统通过扫描发现两个或两个上;如下所示

@Autowired
DataService dataService;


@Repository
public class AsDataService implements DataService{
   
}
 
@Repository
public class BsDataService implements DataService{
   
}

修复方法:

1、增加@Primary注解

在其中一个自动注入的bean上标注@Primary不推荐,自动注入会导入BsDataService ;

@Repository
@Primary
public class BsDataService implements DataService{
   
}

2、 按照名字精确匹配

 
@Autowired
DataService  bsDataService;
 
@Autowired
DataService  asDataService;

3、使用@Qualifier指定名称

 
@Autowired()
@Qualifier("asDataService")
DataService dataService;

二、内部类注入写法

 
public class ShopController {
    @Repository
    public static class DataServiceImpl implements DataService{
        @Override
        public void deleteStudent(int id) {
          
        }
    }
 }
 
@Autowired
@Qualifier("shopController.dataServiceImpl ")
DataService dataServiceImpl;
目录
相关文章
|
1月前
|
XML Java 开发者
Spring Boot中的bean注入方式和原理
Spring Boot中的bean注入方式和原理
242 0
|
1月前
|
Java 应用服务中间件 容器
SpringBoot之Web原生组件注入
SpringBoot之Web原生组件注入
|
3天前
|
Java
springboot字段注入@value细节
springboot字段注入@value细节
10 1
|
1天前
|
Java Linux 程序员
技术笔记:Spring生态研习【五】:Springboot中bean的条件注入
技术笔记:Spring生态研习【五】:Springboot中bean的条件注入
|
1月前
|
Java Spring 容器
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
SpringBoot 使用Quartz执行定时任务对象时无法注入Bean问题
50 1
|
1月前
|
Java
SpringBoot注入出现@org.springframework.beans.factory.annotation.Autowired(required=true)
SpringBoot注入出现@org.springframework.beans.factory.annotation.Autowired(required=true)
45 0
|
1月前
|
JSON Java 数据库连接
属性注入掌握:Spring Boot配置属性的高级技巧与最佳实践
属性注入掌握:Spring Boot配置属性的高级技巧与最佳实践
33 1
|
1月前
|
JSON Java 数据格式
SpringBoot配置文件属性注入
SpringBoot配置文件属性注入
35 0
|
11月前
|
SQL 关系型数据库 MySQL
SpringBoot自定义配置注入的方式:自定义配置文件注入,从mysql读取配置进行注入
SpringBoot自定义配置注入的方式:自定义配置文件注入,从mysql读取配置进行注入
190 0
|
1月前
|
前端开发 Java Spring
使用Spring Boot集成Shiro时出现了无法注入Service的问题
使用Spring Boot集成Shiro时出现了无法注入Service的问题