栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Spring 单例 Bean 底层原理

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Spring 单例 Bean 底层原理

一 Spring 容器理解

Spring 容器就是一个 Map,结构为(beanName,bean 对象)。

二 代码
@Component
public class OrderService {
}

@Component
public class UserService  {
    @Autowired
    private OrderService orderService;

    public UserService(OrderService orderService) {
        this.orderService = orderService;
        System.out.println("2");
    }

    // 告诉 Spring 使用哪个构造方法
    @Autowired
    public UserService(OrderService orderService, OrderService orderService1) {
        System.out.println("3");
    }

    public UserService() {
        System.out.println("1");
    }
}

@ComponentScan("beandemo.service")
public class AppConfig {
    @Bean
    public OrderService orderService1() {
        return new OrderService();
    }

    @Bean
    public OrderService orderService2() {
        return new OrderService();
    }
}

public class Test {
    public static void main(String[] args) {
        // Spring frameWork 只是 Spring 家族中的一个成员,Spring 一共有24个项目
        // context 就是一个构造 Bean 的工厂,或者理解为 Bean 容器
        AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);

        UserService userService = context.getBean("userService", UserService.class);
        System.out.println(context.getBean("orderService", OrderService.class));
        System.out.println(context.getBean("orderService", OrderService.class));
        System.out.println(context.getBean("orderService", OrderService.class));
        System.out.println(context.getBean("orderService1", OrderService.class));
        System.out.println(context.getBean("orderService2", OrderService.class));
    }
}
三 上面代码有多少个 Bean

四 测试结果
3
// 下面三个是单例 Bean
beandemo.service.OrderService@67b467e9 
beandemo.service.OrderService@67b467e9
beandemo.service.OrderService@67b467e9
// 第二个单例 Bean
beandemo.service.OrderService@47db50c5
// 第三个单例 Bean
beandemo.service.OrderService@5c072e3f
五 Spring 容器中找 Bean

有3个 OrderService 类型的单例 Bean,下面代码中到底用哪一个呢?

    public UserService(OrderService orderService) {
        this.orderService = orderService;
        System.out.println("2");
    }

先按类型找,再按名字找。

该容器中有 3 个 OrderService 类型的 Bean(orderService,orderService1,orderService2),只有 orderService 这个 Bean 满足要求。它就是我们要找的。

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/692147.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号