根据Bean名称查找
Spring方式
public static void main(String[] main) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean.xml");
User user = beanFactory.getBean("user");
}
Spring Boot方式
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextUtil() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = applicationContext;
}
public static <T> T getBean(String name) {
return this.applicationContext.getBean(name);
}
}
根据Bean类型查找
Spring方式
# 根据类型查找只有一个bean
public static void main(String[] main) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean.xml");
User user = beanFactory.getBean(User.class);
}
# 根据类型查找存在多个bean
public static void main(String[] main) {
BeanFactory beanFactory = new ClassPathXmlApplicationContext("classpath:/META-INF/bean.xml");
if(beanFactory intanceof ListableBeanFactory) {
ListableBeanFactory listableBeanFactory = (ListableBeanFactory) beanFactory;
Map<String, User> users = listableBeanFactory.getBeansOfType(User.class);
}
}
Spring Boot方式
@Component
public class SpringContextUtil implements ApplicationContextAware {
private static ApplicationContext applicationContext;
public SpringContextUtil() {
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
applicationContext = applicationContext;
}
public static <T> T getBean(Class<T> clazz) {
return this.applicationContext.getBeansOfType(clazz);
}
}