Spring 单例 Bean 底层原理

x33g5p2x  于2022-01-04 转载在 Spring  
字(1.9k)|赞(0)|评价(0)|浏览(350)

一 Spring 容器理解

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

二 代码

@Component
public class OrderService {
}

@Component
public class UserService /*implements InitializingBean*/ {
    @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 满足要求。它就是我们要找的。

相关文章

微信公众号

最新文章

更多