在一个项目中,使用到了 Lombok 的@RequiredArgsConstructor
注解来注入对象
@Service
@RequiredArgsConstructor
public class DeliveryServiceImpl implements DeliveryService {
private final ResourceDao resourceDao;
}
注意:
@RequiredArgsConstructor
是Lombok
库提供的一个注解,用于自动生成一个构造器,这个构造器会为所有用final
修饰 或@NonNull
注解的字段提供参数支持,也就是属性注入。
如果字段没有用final
修饰 或@NonNull
注解,可能会发生注入失败报错的情况,所以如果是不会变动的字段,最好用final
关键字修饰,可能变动的字段用@NonNull
注解。
因为ResourceDao
接口有两个实现类
@Repository("XxxResourceDao")
public class XxxResourceDao implements ResourceDao {...}
@Repository("YyyResourceDao")
public class YyyResourceDaoimplements ResourceDao {...}
分别用XxxResourceDao
和YyyResourceDao
来命名
本想配合@Qualifier
注解来做注入时区分
@Service
@RequiredArgsConstructor
public class DeliveryServiceImpl implements DeliveryService {
@Qualifier("XxxResourceDao")
private final ResourceDao resourceDao;
}
但是发现报错:
Description:
Parameter 0 of constructor in com.hkt.it.ds.ruby.dmg.dmgfulfillmentapigz.service.impl.DeliveryServiceImpl required a single bean, but 2 were found:
- DeliveryResourceDao: defined in file [D:\workspace\dmg-fulfillment-api-gz\target\classes\com\hkt\it\ds\ruby\dmg\dmgfulfillmentapigz\dao\impl\DeliveryResourceDao.class]
- FulfillmentResourceDao: defined in file [D:\workspace\dmg-fulfillment-api-gz\target\classes\com\hkt\it\ds\ruby\dmg\dmgfulfillmentapigz\dao\impl\FulfillmentResourceDao.class]
说找到了两个Bean,不知道注入哪一个
这种情况说明@Qualifier
注解失效了
其实在IDEA
中也有提示:
Lombok does not copy the annotation 'org.springframework beans.factory.annotation.Qualifier’into the constructor
Lombok没有复制@Qualifier
注解到构造器中,所以会失效
解决办法:
在项目根目录下创建一个lombok.config
文件
然后在里面添加一项配置:把@Qualifier
添加进允许复制的注解列表中
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier
然后删除target
文件或者mvn clean
一下,重新构建一下项目即可。