多个bean获取同一个Service,获取的内存地址是同一块;引用bean地址存储在一个map中

文章介绍了如何在Java中使用Spring框架进行依赖注入,包括通过`@Autowired`注解自动为UserService注入OrderService,以及如何利用ApplicationContext初始化UserService中的Map缓存用户信息。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public class UserService {
    public void test() {
        System.out.println("---test----");
    }
}
@Test
    public void doesNotContain1(){
        // 创建Spring容器
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
        // 向容器中注册一个Bean
        applicationContext.registerBean("userService", UserService.class);
        // 启动Spring容器
        applicationContext.refresh();
        // 获取Bean对象
        //多个bean获取同一个Service,获取的内存地址是同一块;引用bean地址存储在一个map中
        UserService userService = (UserService) applicationContext.getBean("userService");
        System.out.println(userService);
        UserService userService1 = (UserService) applicationContext.getBean("userService");
        System.out.println(userService1);
        // 使用Bean对象
        userService.test();
        userService1.test();
    }

现在UserService用到了OrderService,我们可以这么写:

public class UserService {

    @Autowired
    private OrderService orderService;

    public void test(){
        System.out.println(orderService);
    }
}
AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext();
applicationContext.registerBean("userService", UserService.class);
applicationContext.registerBean("orderService", OrderService.class);
applicationContext.refresh();

这样UserService中的orderService属性就自动有值了,这个功能就是Spring给我们提供的,叫做依赖注入。

假如现在UserService中有一个Map,需要缓存一部分用户信息,我们可以通过一下方式来进行初始化:

public class UserService implements InitializingBean {

    @Autowired
    private OrderService orderService;

    private Map<String, User> vipUserInfo = new HashMap<>();

    @Override
    public void afterPropertiesSet() throws Exception {
        vipUserInfo.put("001", new User());
        vipUserInfo.put("002", new User());
        vipUserInfo.put("003", new User());
    }

    public void test(){
        System.out.println(orderService);
        System.out.println(vipUserInfo.size());
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值