Spring学习笔记-通过上下文获取bean

方法一: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)