springboot @Component和@Configuration 下使用@bean区别

提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档


前言

提示:这里可以添加本文要记录的大概内容:

springboot @Component和@Configuration 下使用@bean区别。


提示:以下是本篇文章正文内容,下面案例可供参考

一、@Component

示例:定义两个类使用@bean方式注入

@Component
public class TestBeanConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }

    @Bean
    public RoleService roleService() {
        System.out.println(userService());
        System.out.println(userService());
        return new RoleService();
    }
}
@SpringBootApplication(scanBasePackages = {"pers.yzl.smart.framework.**", "pers.learning.**"})
@ComponentScan(basePackages = {"pers.yzl.smart.framework.**", "pers.learning.**"})
@Slf4j
public class Application {
    public static void main(String[] args) {
        ConfigurableApplicationContext application = SpringApplication.run(Application.class, args);
        TestBeanConfig testBeanConfig = application.getBean(TestBeanConfig.class);
        System.out.println(testBeanConfig);
    }
}

输出结果:

pers.learning.service.UserService@2d313c8c
pers.learning.service.UserService@2df65a56
pers.learning.config.TestBeanConfig@37b01ce2

二、@Configuration

示例:定义两个类使用@bean方式注入,启动类不便

@Configuration
public class TestBeanConfig {
    @Bean
    public UserService userService() {
        return new UserService();
    }

    @Bean
    public RoleService roleService() {
        System.out.println(userService());
        System.out.println(userService());
        return new RoleService();
    }
}

输出结果:

pers.learning.service.UserService@2d313c8c
pers.learning.service.UserService@2df65a56
pers.learning.config.TestBeanConfig$$EnhancerBySpringCGLIB$$a8ee1892@7b5021d1


总结

@Component和@Configuration 下使用@bean区别:
@Component在注入RoleService时, 执行userService()是按照方法执行,每次都是一个新的实例。
@Configuration在注入RoleService时,执行userService()会首先检查是否已经有userService的实例,每次都是同一个实例。
@Configuration中的@Bean 注解的方法都会被动态代理,每次都是同一个实例。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值