方法一:ClassPathXmlApplicationContext --从classpath路径加载配置文件,创建Bean对象
ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
ClassName clazz =(ClassName)ctx.getBean("beanName");
方法二:FileSystemXmlApplicationContext --从指定的目录中加载
ApplicationContext ctx = new FileSystemXmlApplication Context("src/applicationContext.xml");
ClassName clazz =(ClassName)ctx.getBean("beanName");
方法三:Spring提供的工具类WebApplicationContextUtils获取ApplicationContext对象(通过ServletContext对象获得ApplicationContext对象,然后根据它获得需要的类实例)
HttpSession session =request.getSession();
ServletContext context = session.getServletContext(); //arg0.getSession().getServletContext();
ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);
ClassName clazz =(ClassName)ctx.getBean("beanName");
方法四:AnnotationConfigApplicationContext获取上下文
ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SeetConfig.class); // 获得实例
Sheet sheet = (Sheet) applicationContext.getBean("sheet"); //pink
System.out.println(sheet.getColor());
最后
以上就是酷炫棒球最近收集整理的关于Spring学习笔记-通过上下文获取bean的全部内容,更多相关Spring学习笔记-通过上下文获取bean内容请搜索靠谱客的其他文章。
发表评论 取消回复