[{"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}]
一、使用@Component,把bean对象依赖交给Spring容器
注意,该注解不能使用,则说明未添加依赖,需要去该项目pom.xml文件内引入依赖,若该项目只是作为一个存放工具类的子模块项目,没有业务代码编写,则在引入的依赖下加上该配置<scope>provided</scope>表示该依赖只在编译阶段有效,
否则不要加,切记!!!
二、
1、@Bean,在项目主启动类里面加上一个方法,方法里面是new一个该要注入的bean对象并返回
2、如果不想在启动类上,而在其他任意类上接收,则需要在该接收类上额外添加一个注解@Configuration。
三、@Import(对象.class),同上,该注解可以直接在主启动类上使用,也可以在任意其他类上使用,在其他类上使用时也需要加上@Configuration
测试结果:
总结:1、三种方式的使用区别:
@Component:适合在本项目内或者各子项目之间使用,允许去更改要管理的对象,去添加该注解。@Import和@Bean适合引入第三方得资源,我们无法去修改其本来的对象。同时,一般@Import多用与配置资源得对象,@Bean用与普通对象
2、@Bean和@Import在主启动类上跟普通类上的区别:
因为主启动类@SpringBootApplication里包含了@SpringBootConfiguration,@SpringBootConfiguration类又包含了@Configuration配置类,所以主启动类上不需要再添加,该类作用就是读取@Bean标记的类,把他交给spring容器,有兴趣自己去点点,看下他们几个的关系