bean容器
大约 1 分钟javaspring
获取容器中 bean 的数量
该方法只会统计通过使用 Component , Service , Repository 等会产生 Bean 的注解标记的类生成的 bean 而如果通过 DefaultListableBeanFactory.registerSingleton(beanName,singletonObject)
手动向容器添加的 bean 是不会统计到的
private ApplicationContext applicationContext;
int count = applicationContext.getBeanDefinitionCount();
手动向容器添加 bean
@Autowired
private ApplicationContext applicationContext;
public Boolean addBean(String beanName,Object singletonObject){
//将applicationContext转换为ConfigurableApplicationContext
ConfigurableApplicationContext configurableApplicationContext = (ConfigurableApplicationContext) applicationContext;
//获取BeanFactory
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) configurableApplicationContext.getAutowireCapableBeanFactory();
//动态注册bean.
defaultListableBeanFactory.registerSingleton(beanName,singletonObject);
return true;
}
从容器中获取 bean
概述
不管是自己制作的类还是 spring 通过检测自动创建的 bean 都可以从容器中获取,大致分为两种方式:根据 bean 名称、根据类名。可直接通过 Autowired 自动装配,也可以通过上下文 ApplicationContext 调用方法 getBean 获取
获取 Bean 的方法
自动装配 - Autowired
@Autowired
private SqlSessionFactory sqlSessionFactory;
获取SqlSessionFactory 类型的 bean之后可获取数据库以及 mybatis 相关的数据,执行的 sql 语句以及参数等等。通过该 Bean 打印拼接参数后的 sql 点击我查看文章。
通过 ApplicationContext 获取
@Autowired
private ApplicationContext applicationContext;
SqlSessionFactory sqlSessionFactory = applicationContext.getBean(SqlSessionFactory.class);
实现接口BeanFactoryAware
实现了该接口的类会由 spring 自动注入 BeanFactory,那么在类内部使用该属性就可以获取容器内的其他 bean 了
public class MyBeanFactory implements BeanFactoryAware {
private BeanFactory beanFactory;
@Override
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = beanFactory;
}
public void getMyBeanName() {
MyBeanName myBeanName = beanFactory.getBean(MyBeanName.class);
System.out.println(beanFactory.isSingleton("myCustomBeanName"));
}
}
