Chinaunix首页 | 论坛 | 博客
  • 博客访问: 491418
  • 博文数量: 78
  • 博客积分: 1271
  • 博客等级: 中尉
  • 技术积分: 1108
  • 用 户 组: 普通用户
  • 注册时间: 2011-01-14 14:39
文章分类

全部博文(78)

文章存档

2015年(2)

2014年(6)

2013年(15)

2012年(18)

2011年(37)

分类: Java

2014-01-16 22:40:27

   Spring编程式注入,可以清楚地看到Spring的类层次结构。
   

   我们来看看具体的例子:
    1.App类;
      public class App {
            private Person person;
      }

    2.Person类; 
       public class Person {
            private String name;
            private String age;
       }

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;
  
 }

}

           
  
阅读(2525) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~