在非web环境中,常用ClassPathXmlApplicationContext来创建ApplicationContext
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
下面以ClassPathXmlApplicationContext来看加载流程。
public static void main(String[] args) throws ClassNotFoundException { //1 声明BeanDefinition BeanDefinition userDaoDefinition = new RootBeanDefinition(UserDao.class); BeanDefinition beanDefinition = BeanDefinitionReaderUtils.createBeanDefinition(null, User33Service.class.getName(), null); //2 创建BeanFactory,并注册beanDefinitions beanDefinition.getPropertyValues().addPropertyValue("userDao", new RuntimeBeanReference("userDao")); List<Integer> values = new ManagedList<>(); values.add(1); values.add(2); values.add(3); beanDefinition.getPropertyValues().addPropertyValue("values", values); DefaultListableBeanFactory beanFactory = new DefaultListableBeanFactory(); beanFactory.registerBeanDefinition("userService", beanDefinition); beanFactory.registerBeanDefinition("userDao", userDaoDefinition); User33Service user33Service = (User33Service) beanFactory.getBean("userService"); System.out.println(user33Service.getUser()); } 复制代码
BeanDefinition中通过 beanDefinition.getPropertyValues().addPropertyValue 设置bean的属性。
Spring中的ApplicationContext基本都是继承自AbstractRefreshableConfigApplicationContext,比如ClassPathXmlApplicationContext,FileSystemXmlApplicationContext等。
自定义ApplicationContext:
public class MyContext extends AbstractRefreshableConfigApplicationContext { public MyContext(){ super.addApplicationListener(new MyListener()); super.refresh(); } @Override protected void loadBeanDefinitions(DefaultListableBeanFactory beanFactory) throws BeansException, IOException { RootBeanDefinition beanDefinition = new RootBeanDefinition(CustomService.class); beanFactory.registerBeanDefinition("testBean", beanDefinition); beanFactory.registerBeanDefinition("childBean", new GenericBeanDefinition(beanDefinition)); GenericBeanDefinition genericBeanDefinition = new GenericBeanDefinition(); genericBeanDefinition.setBeanClass(CustomService.class); beanFactory.registerBeanDefinition("genericBean", genericBeanDefinition); } } 复制代码
1.继承AbstractRefreshableConfigApplicationContext;
2.实现loadBeanDefinitions;
3.创建BeanDefinition(AbstractBeanDefinition, RootBeanDefinition, 或 GenericBeanDefinition);
4.通过beanDefinition.getPropertyValues().addPropertyValue设置bean的属性;
5.beanFactory.registerBeanDefinition注册bean。