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());
}
}