总结:有时候我们想获取容器中的bean 代码获取,那么首先要获取工厂对象 ,那么我总结一下几种常用的方式吧。
基本使用如下
1.获取数据从applicationContext
//所有实现类的name
String[] list = applicationContext.getBeanNamesForType(FileService.class);
//单个
//List<FileService> list = (List)applicationContext.getBean(FileService.class);
System.out.println(Arrays.asList(list));
//对个 key name value 对象
Map map = applicationContext.getBeansOfType(FileService.class);
System.out.println(map);
//所有bean
String[] beanDefinitionNames = applicationContext.getBeanDefinitionNames();
System.out.println(Arrays.asList(beanDefinitionNames));
//发布一个事件
SpringUtils.publishEvent(new UserRegisterEvent(user));
2.动态注入bean
//动态注入bean
DefaultListableBeanFactory defaultListableBeanFactory = (DefaultListableBeanFactory) ctx.getAutowireCapableBeanFactory();
//创建bean信息.
BeanDefinitionBuilder beanDefinitionBuilder = BeanDefinitionBuilder.genericBeanDefinition(Dept.class);
//添加属性值
beanDefinitionBuilder.addPropertyValue("deptName","快乐风男");
defaultListableBeanFactory.registerBeanDefinition("dept", beanDefinitionBuilder.getBeanDefinition());
System.out.println(ctx.getBean("dept"));
//删除bean.
defaultListableBeanFactory.removeBeanDefinition("dept");
获取几种方式如下:
1.直接注入
@Resource
private ApplicationContext ctx;
2.直接文件系统获取
String xmlPath = "WebContent/WEB-INF/config/base/applicationContext.xml";
ApplicationContext ac = new FileSystemXmlApplicationContext(xmlPath);
3.classpath 获取
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
4.WebApplicationContextUtils 获取
// Spring中获取ServletContext对象,普通类中可以这样获取
ServletContext sc = ContextLoader.getCurrentWebApplicationContext().getServletContext();
// servlet中可以这样获取,方法比较多
ServletContext sc = request.getServletContext():
ServletContext sc = servletConfig.getServletContext(); //servletConfig可以在servlet的init(ServletConfig config)方法中获取得到
/* 需要传入一个参数ServletContext对象, 获取方法在上面 */
// 这种方法 获取失败时抛出异常
ApplicationContext ac = WebApplicationContextUtils.getRequiredWebApplicationContext(sc);
// 这种方法 获取失败时返回null
ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(sc);
5.实现ApplicationContextAware接口
@Component
public class SpringUtils implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.applicationContext = applicationContext;
}
6.注解方式
ApplicationContext ctx = new AnnotationConfigServletWebServerApplicationContext(DemoApplication.class);