Spring study notes-get bean through context

Method 1: ClassPathXmlApplicationContext - Load configuration files from the classpath path and create Bean objects

ApplicationContext ctx = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");

ClassName clazz =(ClassName)ctx.getBean("beanName");

 

Method 2: FileSystemXmlApplicationContext-Load from the specified directory

ApplicationContext ctx = new FileSystemXmlApplication Context("src/applicationContext.xml");

ClassName clazz =(ClassName)ctx.getBean("beanName");

 

Method 3: The tool class WebApplicationContextUtils provided by Spring obtains the ApplicationContext object (obtains the ApplicationContext object through the ServletContext object, and then obtains the required class instance according to it)

HttpSession session =request.getSession();

ServletContext context = session.getServletContext();  //arg0.getSession().getServletContext();

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(context);

ClassName clazz =(ClassName)ctx.getBean("beanName");

 

Method 4: AnnotationConfigApplicationContext obtains the context

ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SeetConfig.class); // 获得实例

Sheet sheet = (Sheet) applicationContext.getBean("sheet"); //pink

System.out.println(sheet.getColor());

Guess you like

Origin blog.csdn.net/mumuwang1234/article/details/113738270