Spring IoC 依赖查找

2023/04/06 posted in  Spring IoC

根据Bean 名称查找

  • 实时查找
 // 配置 XML 配置文件
 // 启动 Spring 应用上下文
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/lookup-context.xml");
User user = (User) beanFactory.getBean("user");
  • 延迟查找
 // 配置 XML 配置文件
 // 启动 Spring 应用上下文
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/lookup-context.xml");
ObjectFactory<User> objectFactory = (ObjectFactory<User>) beanFactory.getBean("objectFactory");
User user = objectFactory.getObject();

根据Bean 类型查找

  • 单个Bean 对象
 // 配置 XML 配置文件
 // 启动 Spring 应用上下文
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/lookup-context.xml");
User user = beanFactory.getBean(User.class);
  • 集合Bean 对象
 // 配置 XML 配置文件
 // 启动 Spring 应用上下文
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/lookup-context.xml");
if (beanFactory instanceof ListableBeanFactory) {
    ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
    Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
}

根据Bean 名称 + 类型查找

根据Java 注解查找

  • 单个Bean 对象
  • 集合Bean 对象
 // 配置 XML 配置文件
 // 启动 Spring 应用上下文
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/lookup-context.xml");
if (beanFactory instanceof ListableBeanFactory) {
    ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
    Map<String, User> users = (Map) listableBeanFactory.getBeansWithAnnotation(Super.class);
}