易错题-configuration和一般的component区别

学习内容见:聊透spring @Configuration配置类
通过片段思考结果:
component代码片段

@Component
public class ComponentTest {

    @Bean
    public User a(){
        System.out.println("ComponentTest A----");
        return new User();
    }
    @Bean
    public User b(){
        a();
        System.out.println("ComponentTest B----");
        return new User();
    }

    @Scheduled(initialDelay = 2000,fixedDelay = 20000)
    public void execute(){
        System.out.println("ComponentTest execute----");
        b();
    }
}

先输出
ComponentTest A----
ComponentTest A----
ComponentTest B----
然后定时输出
ComponentTest execute----
ComponentTest A----
ComponentTest B----

configuration代码片段

@Configuration
public class ConfigurationTest {
    @Bean
    public User a1(){
        System.out.println("ConfigurationTest A----");
        return new User();
    }
    @Bean("b1")
    public User b1(){
        a1();
        System.out.println("ConfigurationTest B----");
        return new User();
    }

    @Scheduled(initialDelay = 2000,fixedDelay = 20000)
    public void execute(){
        System.out.println("ConfigurationTest execute----");
        b1();
    }
}

先输出
ConfigurationTest A----
ConfigurationTest B----
然后定时输出
ConfigurationTest execute----

总结:对于使用configuration中配置的bean,其底层会对方法a1()、b1()加上拦截器,对于调用方法a1,拦截器拦截后,本质上从spring容器中直接取出a1的内容,该内容底层使用的是代理的方式实现的,因此运行结果上看a1中的方法没有在b1中执行

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值