在我们项目中可能会遇到@resource、@Autowired引用的接口会有多个实现类的情况,下面针对我所遇到的情况记录下,如有遗留或者叙述错误的地方,望各位大佬们针对性指出,悉心学习~
传统的Spring做法是使用.xml文件来对bean进行注入,所有的内容都需要配置在.xml文件中,使配置和编程分离,却增加了可读性和复杂度。
@Resource按byName自动注入,@Autowired按byType自动注入;
@Resource(name=“imageEncodeInfoService”)
private ImageEncodeInfoService imageEncodeInfoService;
@@Resource既没指定name,也没指定type时则自动按照byName方式进行装配。
@Resource
private ImageEncodeInfoService imageEncodeInfoService;
@Resource若没有name属性,实现类里有@ConditionalOnProperty注解
@Resource
private ImageEncodeInfoService imageEncodeInfoService;
接口
public interface ImageEncodeInfoService {
void imageInfoEncodeServer(String a);
}
ServiceImpl层:实现类A
@Service
@ConditionalOnProperty(value = “springBean.edition”, havingValue = “a”)
public class ImageInfoEncodeServerA implements ImageEncodeInfoService {
@Override
public void imageInfoEncodeServer(String v) {}}
ServiceImpl层:实现类B
@Service
@ConditionalOnProperty(value = “springBean.edition”, havingValue = “b”)
public class ImageInfoEncodeServerB implements ImageEncodeInfoService {
@Override
public void imageInfoEncodeServer(String v) {}}
常见的@ConditionalOnxxx开头的注解我们称之为条件注解,常见的条件注解有
class条件注解:@ConditionalOnClass
bean条件注解:@ConditionalOnBean
属性条件注解:@ConditionalOnProperty
@ConditionalOnProperty注解指,针对配置文件里配置的信息,去@Bean注入对应的实现类
#application.yml配置文件
springBean:
edition: a
这样配置,会引用实现类A;