[{"createTime":1735734952000,"id":1,"img":"hwy_ms_500_252.jpeg","link":"https://activity.huaweicloud.com/cps.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=V1g3MDY4NTY=&utm_medium=cps&utm_campaign=201905","name":"华为云秒杀","status":9,"txt":"华为云38元秒杀","type":1,"updateTime":1735747411000,"userId":3},{"createTime":1736173885000,"id":2,"img":"txy_480_300.png","link":"https://cloud.tencent.com/act/cps/redirect?redirect=1077&cps_key=edb15096bfff75effaaa8c8bb66138bd&from=console","name":"腾讯云秒杀","status":9,"txt":"腾讯云限量秒杀","type":1,"updateTime":1736173885000,"userId":3},{"createTime":1736177492000,"id":3,"img":"aly_251_140.png","link":"https://www.aliyun.com/minisite/goods?userCode=pwp8kmv3","memo":"","name":"阿里云","status":9,"txt":"阿里云2折起","type":1,"updateTime":1736177492000,"userId":3},{"createTime":1735660800000,"id":4,"img":"vultr_560_300.png","link":"https://www.vultr.com/?ref=9603742-8H","name":"Vultr","status":9,"txt":"Vultr送$100","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":5,"img":"jdy_663_320.jpg","link":"https://3.cn/2ay1-e5t","name":"京东云","status":9,"txt":"京东云特惠专区","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":6,"img":"new_ads.png","link":"https://www.iodraw.com/ads","name":"发布广告","status":9,"txt":"发布广告","type":1,"updateTime":1735660800000,"userId":3},{"createTime":1735660800000,"id":7,"img":"yun_910_50.png","link":"https://activity.huaweicloud.com/discount_area_v5/index.html?fromacct=261f35b6-af54-4511-a2ca-910fa15905d1&utm_source=aXhpYW95YW5nOA===&utm_medium=cps&utm_campaign=201905","name":"底部","status":9,"txt":"高性能云服务器2折起","type":2,"updateTime":1735660800000,"userId":3}]
<>场景:使用 @Autowired 的时候,到底是写接口还是实现类?
<>答案:写的接口
<>当实现类唯一时,表面上注入接口,其实注入实现类
<>当实现类多个时,通过@Service(“menuService1”)指定实现类
<>解析:
这个其实是创建了实现类的对象但引用了接口类型,
即 “InjectionDao injectionDao = new InjectionDaoImpl ()”, 是 Java 多态性(向上转型)的一种应用。
在实现类处加 @Repository 注解,意思就是 new InjectionDaoImpl (),
而在 InjectionServiceImpl 中定义属性 InjectionDAO injectionDAO 就是将 new 出来的这个
InjectionDaoImpl 对象向上转型为 InjectionDao 类型。
<>注意:
若一个接口被多个实现类,实现的时候,@Autowired,Spring 会按 byType
的方式寻找接口的实现类,将其注入。存在多个实现类,应该指定名字,可以通过 byName 注入的方式。可以使用 @Resource 或 @Qualifier
注解。
//实现类1 @Service("menuService1") public class MenuServiceImpl implements
IMenuService //实现类2 @Service("menuService2") public class MenuServiceImpl
implements IMenuService //注入接口,相当于new一个实现类,指定名称menuService1实现类 @Autowired @
Qualifier("menuService1") private IMenuService menuService;
//注入接口,相当于new一个实现类,指定名称menuService2实现类 @Autowired @Qualifier("menuService2")
private IMenuService menuService;