全部博文(78)
分类: Java
2014-01-16 22:40:27
package com.oristartech.inject;
import org.springframework.beans.MutablePropertyValues;
import org.springframework.beans.PropertyValue;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.config.BeanDefinition;
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 com.oristartech.springexample.App;
import com.oristartech.springexample.Person;
public class CodeInject {
public static void main(String[] args) {
DefaultListableBeanFactory beanRegistry = new DefaultListableBeanFactory();
BeanFactory container = (BeanFactory)injectViaCode(beanRegistry);
App at = (App) container.getBean("app");
System.out.println(at.getPerson().getName());
System.out.println(at.getPerson().getAge());
}
private static BeanFactory injectViaCode(BeanDefinitionRegistry beanRegistry) {
AbstractBeanDefinition newPerson = new RootBeanDefinition(Person.class);
newPerson.setScope(BeanDefinition.SCOPE_SINGLETON);
AbstractBeanDefinition newApp = new RootBeanDefinition(App.class);
newApp.setScope(BeanDefinition.SCOPE_SINGLETON);
//将bean定义注册到容器中
beanRegistry.registerBeanDefinition("app", newApp);
beanRegistry.registerBeanDefinition("person", newPerson);
//setter方法注入
MutablePropertyValues personProps = new MutablePropertyValues();
personProps.add("name", "suhaoyuan")
.add("age", "20");
newPerson.setPropertyValues(personProps);
MutablePropertyValues appProps = new MutablePropertyValues();
appProps.add("person", newPerson);
newApp.setPropertyValues(appProps);
return (BeanFactory)beanRegistry;
}
}