Lombokの@RequiredArgsConstructorでコンストラクタインジェクションする際に@QualifierアノテーションでBean指定してもエラーとなる
AppConfigクラスでBeanをname属性を指定して指定します。
package jp.co.confrage.config; | |
import org.springframework.context.annotation.Bean; | |
import org.springframework.context.annotation.Configuration; | |
import org.springframework.web.client.RestTemplate; | |
@Configuration | |
public class AppConfifg { | |
@Bean(name = "restTemplate1") | |
public RestTemplate restTemplate1() { | |
var ret = new RestTemplate(); | |
return ret; | |
} | |
@Bean(name = "restTemplate2") | |
public RestTemplate restTemplate2() { | |
var ret = new RestTemplate(); | |
return ret; | |
} | |
} |
Lombokの@RequiredArgsConstructorアノテーションでコンストラクタインジェクションを使用した際に、@QualifierアノテーションでBean名を指定してインジェクションしようとすると、「Parameter 0 of constructor in jp.co.confrage.presentation.controller.XXXController required a single bean, but 2 were found」というエラーが発生します。
回避するには、プロジェクト直下にlombok.configというファイルを作成し、以下1行記述します。
コントローラクラスにprivate finalで@Qualifierを指定します。
package jp.co.confrage.presentation.controller; | |
import org.springframework.beans.factory.annotation.Qualifier; | |
import org.springframework.web.bind.annotation.PathVariable; | |
import org.springframework.web.bind.annotation.RequestMapping; | |
import org.springframework.web.bind.annotation.RequestMethod; | |
import org.springframework.web.bind.annotation.RestController; | |
import org.springframework.web.client.RestTemplate; | |
import lombok.RequiredArgsConstructor; | |
@RestController | |
@RequiredArgsConstructor | |
public class XXXController { | |
@Qualifier("restTemplate1") | |
private final RestTemplate restTemplate1; | |
@Qualifier("restTemplate2") | |
private final RestTemplate restTemplate2; | |
@RequestMapping(path = "/{userId}" + "/{pass}", method = RequestMethod.GET) | |
public void signin(@PathVariable String userId, @PathVariable String pass) { | |
// 省略 | |
} | |
} |
これでエラーは回避されます。
KHI入社して退社。今はCONFRAGEで正社員です。関西で140-170/80~120万から受け付けております^^
得意技はJS(ES6),Java,AWSの大体のリソースです
コメントはやさしくお願いいたします^^
座右の銘は、「狭き門より入れ」「願わくは、我に七難八苦を与えたまえ」です^^