(II)第三节:Bean的注册与获取

一、注册 Bean

  基于 XML 配置的方式,可以在 Spring 的配置文件中使用 bean 标签来配置 bean 的信息。

  Person 类的声明:

1 public class Person {
2     private String lastName;
3     private Integer age;
4     private String gender;
5     private String email;
6     //构造器与 setter & getter  
7 }

 

  使用 bean 标签在配置文件中注册:  

    <!--注册一个Person对象,Spring会自动创建这个Person对象-->
    <!--
        一个bean标签可以注册一个组件(对象,类)
        class:写要注册的组件全类名
        id:这个对象的唯一标识
    -->
    <bean id="person01" class="com.njf.spring.bean.Person">
        <!--
            使用property标签为Person对象的属性赋值
            name="lastName": 指定属性名
            value="子龙": 指定属性值
         -->
        <property name="lastName" value="子龙"></property>
        <property name="age" value="18"></property>
        <property name="email" value="zilong@achang.com"></property>
        <property name="gender" value="男"></property>
    </bean>

 

 

 

二、获取 Bean

  我们知道可以通过ApplicationContext的getBean方法来获取Spring容器中已初始化的bean。getBean一共有以下四种方法原型:

  一共有以下四种方法原型:

getBean(String name)

getBean(Class<T> type)

getBean(String name,Class<T> type)

getBean(String name,Object[] args)

 

  (1)方式一

public Object getBean(String name) throws BeansException

    这个方法应该是通过bean的名称来得到bean的对象,实现了接口beanfactory,返回一个独立或者被共享的bean实例。

    测试:

      注册:在 ioc.xml 的配置文件中注册一个 bean

    <bean id="person01" class="com.njf.spring.bean.Person">
        <property name="lastName" value="子龙"></property>
        <property name="age" value="18"></property>
        <property name="email" value="zilong@achang.com"></property>
        <property name="gender" value="男"></property>
    </bean>

 

      获取:

      参数 name 表示IOC容器中已经实例化的bean的id或者name,且无论是 id 还是name都要求在IOC容器中是唯一的不能重名。那么这种方法就是通过id或name去查找获取bean.获取bean的参考代码如下:

   @Test
   public void testGetBean1() {
      ApplicationContext ioc = new ClassPathXmlApplicationContext("ioc.xml");

      Person person01 = (Person) ioc.getBean("person01");
      System.out.println("person01 = " + person01);
   }

 

      

  (2)方式二

public <T> T getBean(String name, Class<T> requiredType) throws BeansException

    这个方法通过bean的名称和想要获取的bean匹配的类型来获取bean,类型可以是一个接口或者是父类,可以为空(即匹配任意类型),同样返回一个独立或者被共享的bean实例

    

 

  (3)方式三

public <T> T getBean(Class<T> requiredType) throws BeansException

    这个方法通过想要获取的bean匹配的类型来获取bean,类型可以是一个接口或者是父类,不可以为空,返回一个匹配到的bean实例

    参数Class<T> type表示要加载的Bean的类型。如果该类型没有继承任何父类(Object类除外)和实现接口的话,那么要求该类型的bean在IOC容器中也必须是唯一的。比如applicationContext.xml配置两个类型完全一致的bean,且都没有配置id和name属性。

    测试代码:

    

 

  (4)方式四

public Object getBean(String name, Object... args) throws BeansException

    这个方法通过bean的名称和一些bean的参数来获取bean,(only applied when creating a new instance as opposed to retrieving an existing one)好像是说只能在bean初始化的时候用。

 

 

  

 

上一篇:爬虫学习(1):urllib教程


下一篇:springboot @Import注解 @EnableAutoConfiguration 注解