- package domain;
- import core.config.Beans;
- import org.junit.Before;
- import org.junit.Test;
- import org.springframework.beans.factory.support.DefaultListableBeanFactory;
- import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.annotation.AnnotationConfigApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import org.springframework.core.io.Resource;
- import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
- import org.springframework.core.io.support.ResourcePatternResolver;
- import java.io.IOException;
- /**
- * @author 王杨帅
- * @create 2018-08-10 20:47
- * @desc 测试类
- **/
- public class TestDemo {
- @Before
- public void init() {System.out.println("初始化方法");
- }
- /**
- * 利用 BeanFactory 获取 bean
- * @throws IOException
- */
- @Test
- public void test01() throws IOException {
- System.out.println("Hello Boy");
- ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
- Resource resource = resolver.getResource("classpath:applicationContext.xml");
- System.out.println(resource.getURL());
- DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
- XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader(factory);
- reader.loadBeanDefinitions(resource);
- System.out.println("初始化 BeanFactory 完毕");
- Student student = factory.getBean("student", Student.class);
- System.out.println("student bean 获取成功");
- student.info();
- }
- /**
- * 利用 ApplicationContext 獲取 bean
- */
- @Test
- public void test02() {
- ApplicationContext applicationContext = new ClassPathXmlApplicationContext("classpath:applicationContext.xml");
- Student student = applicationContext.getBean("student", Student.class);
- student.info();
- }
- /**
- * 利用 ApplicationContext 获取配置类配置的 bean
- */
- @Test
- public void test03() {
- ApplicationContext applicationContext = new AnnotationConfigApplicationContext(Beans.class);
- Teacher teacher = applicationContext.getBean("teacher", Teacher.class);
- teacher.info();
- }
- }
来源: https://www.cnblogs.com/NeverCtrl-C/p/9457434.html