import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.DefaultListableBeanFactory;
import org.springframework.beans.factory.support.RootBeanDefinition;
import org.springframework.beans.factory.xml.XmlBeanDefinitionReader;
public class IocTester {
@Test
public void testBeanFactoryGenerateBeans_bindViaCode() {
DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();
BeanFactory beanFactory = bindViaCode(beanRegistry);
UserService userService = (UserService) beanFactory.getBean("userService");
userService.add(new User());
}
@Test
public void testBeanFactoryGenerateBeans_bindViaXml() {
DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();
BeanFactory beanFactory = bindViaXML(beanRegistry);
UserService userService = (UserService) beanFactory.getBean("userService");
userService.add(new User());
}
public BeanFactory bindViaCode(BeanDefinitionRegistry registry) {
AbstractBeanDefinition userService = new RootBeanDefinition(UserService.class);
AbstractBeanDefinition userDAOImpl = new RootBeanDefinition(UserDAOImpl.class);
registry.registerBeanDefinition("userService", userService);
registry.registerBeanDefinition("userDAO", userDAOImpl);
MutablePropertyValues propertyValues = new MutablePropertyValues();
propertyValues.addPropertyValue(new PropertyValue("userDAO", userDAOImpl));
userService.setPropertyValues(propertyValues);
return (BeanFactory) registry;
}
public BeanFactory bindViaXML(BeanDefinitionRegistry registry) {
XmlBeanDefinitionReader xmlBeanDefinitionReader = new XmlBeanDefinitionReader(registry);
xmlBeanDefinitionReader.loadBeanDefinitions("classpath:ioc/applicationContext-ioc-bean.xml");
return (BeanFactory) registry;
}
}