仿照 Spring 实现的一个简易版的 IoC 容器。
- 支持根据指定的路径从文件系统中获取资源
- 支持XSD模式的XML验证
- 支持
<property/>
标签以及value
与ref
属性(即字符串与引用类型的属性注入) - 支持单例与原型Bean,并通过三级缓存解决了单例Bean的循环依赖问题
- 扩展资源加载策略,如支持类路径与URL形式的资源
- 提供
byName
与byType
方式的自动装配,以及@Autowired
注解 - 实现
ApplicationContext
体系
第一个测试是模拟登陆接口的场景,分为Controller
、Service
、Dao
三层,XML配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="loginController" class="cn.hecenjie.simpleioc.tests.objects.login.LoginController">
<property name="loginService" ref="loginService" />
</bean>
<bean id="loginService" class="cn.hecenjie.simpleioc.tests.objects.login.LoginServiceImpl">
<property name="userDao" ref="userDao" />
</bean>
<bean id="userDao" class="cn.hecenjie.simpleioc.tests.objects.login.UserDao"/>
</beans>
测试代码如下:
@Test
public void testGetBean() {
ResourceLoader resourceLoader = new FileSystemResourceLoader();
Resource resource = resourceLoader.getResource("C:\\Users\\canjie\\Desktop\\login.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(factory);
beanDefinitionReader.loadBeanDefinitions(resource);
LoginController loginController = (LoginController) factory.getBean("loginController");
assertEquals(loginController.login("Lihua", "123456789"), true);
}
第二个测试是针对循环依赖问题的,XML配置文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-2.0.xsd">
<bean id="person" class="cn.hecenjie.simpleioc.tests.objects.persons.Person">
<property name="name" value="Lihua" />
<property name="age" value="18" />
<property name="idCard" ref="idCard" />
</bean>
<bean id="idCard" class="cn.hecenjie.simpleioc.tests.objects.persons.IdCard">
<property name="id" value="441301188875468912" />
<property name="owner" ref="person" />
</bean>
</beans>
测试代码如下:
@Test
public void testCyclicDependence(){
ResourceLoader resourceLoader = new FileSystemResourceLoader();
Resource resource = resourceLoader.getResource("C:\\Users\\canjie\\Desktop\\persons.xml");
DefaultListableBeanFactory factory = new DefaultListableBeanFactory();
BeanDefinitionReader beanDefinitionReader = new XmlBeanDefinitionReader(factory);
beanDefinitionReader.loadBeanDefinitions(resource);
Person person = (Person) factory.getBean("person");
IdCard idCard = (IdCard) factory.getBean("idCard");
assertEquals(person.getName(), "Lihua");
assertEquals(person.getAge(), 18);
assertEquals(person.getIdCard(), idCard);
assertEquals(idCard.getId(), 441301188875468912L);
assertEquals(idCard.getOwner(), person);
}