---
# System prepended metadata

title: '@Autowired無法自動注入有多個implement之解法'
tags: ['@Primary', '@Resource', '@Autowired', Spring]

---

# @Autowired無法自動注入有多個implement之解法

###### tags: `Spring` `@Autowired` `@Resource` `@Primary`

```=java

Field supChargesService in com.ysdt.schedule.service.sup.charges.ActSupportService required a single bean, but 3 were found:
	- supSupplierChargesInvoiceService: defined in file [C:\workSpace2022\S_cashFlow\target\classes\com\ysdt\schedule\service\sup\charges\SupSupplierChar
gesInvoiceService.class]
	- supSupplierChargesReportService: defined in file [C:\workSpace2022\S_cashFlow\target\classes\com\ysdt\schedule\service\sup\charges\SupSupplierCharg
esReportService.class]
	- supSupplierChargesService: defined in file [C:\workSpace2022\S_cashFlow\target\classes\com\ysdt\schedule\service\sup\charges\SupSupplierChargesServ
ice.class]


Action:

Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be
 consumed

```

在設定自動注入時，發現當類別有多個實現類別，導致會無法注入。

上網查詢解法為下:
1. 將@Autowired換成@Resource（name = "指定注入Bean的名稱"）
    ```=java
    @Resource(name = "redisService",type = IRedisTemplate.class)
    private IRedisTemplate redisService;
    ```
2. 使用@Qualifier（"指定注入Bean的名稱"）
    ```=java
    @Autowired
    @Qualifier("redisService")
    private IRedisTemplate redisService;

    ```
    
目前使用了1與2的解法
皆無法解決無法開啟的問題。
後來與公司前輩探討，有可能那隻程式比較久了 所以會一直無法判別
就直接在主要的父類別設上@Primary(當作預設)

這才解決了這個問題。

以下為範例 :

> **Controller**

```=java

@Resource(name = "studentService",type = StudentService.class)
private StudentService studentService;

```
> **Service**
```=java

@Service("studentService")
@Slf4j
@Primary
public class StudentService {

...
....
}

```