在非web環境中,經常使用ClassPathXmlApplicationContext來建立ApplicationContextjava
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
web
下面以ClassPathXmlApplicationContext來看加載流程。spring
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的屬性。app
- 屬性:
- ref : RuntimeBeanReference
- value : TypedStringValue
- property的子標籤:
- bean: BeanDefinitionHolder
- ref : RuntimeBeanReference
- idref : RuntimeBeanNameReference
- value : TypedStringValue
- null : TypedStringValue
- array : ManagedArray or List 代碼中已經被強制轉換爲List
- list : ManagedList or List 代碼中已經被強制轉換爲List
- set : ManagedSet or Set 代碼中已經被強制轉換爲Set
- map : ManagedMap or Map 代碼中已經被強制轉換爲Map
- props : ManagedProperties
Spring中的ApplicationContext基本都是繼承自AbstractRefreshableConfigApplicationContext,好比ClassPathXmlApplicationContext,FileSystemXmlApplicationContext等。ide
自定義ApplicationContext:spa
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,註冊bean。
1.繼承AbstractRefreshableConfigApplicationContext;code
2.實現loadBeanDefinitions;cdn
3.建立BeanDefinition(AbstractBeanDefinition, RootBeanDefinition, 或 GenericBeanDefinition);xml
4.經過beanDefinition.getPropertyValues().addPropertyValue設置bean的屬性;對象
5.beanFactory.registerBeanDefinition註冊bean。