Spring 实例化bean的方式

Spring bean是由Spring IoC容器管理的对象。Spring IoC容器管理一个或多个bean,这些bean以XML配置或者基于java配置元数据的形式提供给容器。

在spring框架中,IoC容器可以通过以下四种方式实例化bean:

  • 构造函数实例化
  • 静态工厂方法实例化
  • 实例工厂方法实例化
  • FactoryBean实例化

1、使用构造函数实例化bean

调用类的构造函数获取对应的bean实例,是使用最多的方式,这种方式只需要在xml bean元素中指定class属性,spring容器内部会自动调用该类型的构造函数来创建bean对象,将其放在容器中以供使用。

以下是具有默认构造函数的Bean类。

MyBean.java

package com.boraji.tutorial.spring;

public class MyBean {

   public MyBean() {
      System.out.println("MyBean is initialized!!");
   }

   public void saySomething() {
      System.out.println("I'm inside saySomething() method.");
   }
}

这是一个XML配置元数据,我们可以在其中指定我们的bean,如下所示。

beans.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 http://www.springframework.org/schema/beans/spring-beans.xsd">

	<bean id="myBean" class="com.boraji.tutorial.spring.MyBean" />
</beans>

MainApp.java

package com.boraji.tutorial.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
		MyBean bean=context.getBean("myBean", MyBean.class);
		bean.saySomething();
	}

}

输出

MyBean is initialized!!
I'm inside saySomething() method.

2、使用静态工厂方法实例化bean

在这种机制中,Spring IoC容器通过调用由XML配置元数据中元素的class属性指定的类的静态工厂方法来创建一个新bean。

元素的属性factory-method指定静态方法的名称。

以下是带有静态工厂方法的类。

MyService.java

package com.boraji.tutorial.spring;

public class MyService {

   private static MyService myService;

   private MyService() {
      System.out.println("Inside MyService private constructor. ");
   }

   // Static factory method
   public static MyService getInstance() {
      if (myService == null) {
         myService = new MyService();
      }
      return myService;
   }

   public void doSomething() {
      System.out.println("Inside doSomething method");
   }
}

XML配置元数据,我们可以在其中指定我们的静态工厂方法,如下所示。

beans.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean id="myService" class="com.boraji.tutorial.spring.MyService" factory-method="getInstance"/>
</beans>

MainApp.java

package com.boraji.tutorial.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
      MyService myService = context.getBean("myService", MyService.class);
      myService.doSomething();
   }

}

输出

Inside MyService private constructor. 
Inside doSomething method

3、使用实例工厂方法实例化bean

与通过静态工厂方法实例化类似,Spring IoC容器从容器中调用现有bean的非静态方法来创建新bean。

这是带有实例工厂方法的类。

MyService.java

package com.boraji.tutorial.spring;

public class MyService {

   private MyService() {
      System.out.println("Inside MyService private constructor.");
   }

   // Instance factory method
   public MyService createService() {
      return new MyService();
   }

   public void doSomething() {
      System.out.println("Inside doSomething method");
   }
}

XML配置元数据,其中我们使用的factory-bean和factory-method属性指定了实例工厂和方法。

beans.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 http://www.springframework.org/schema/beans/spring-beans.xsd">
	
	<bean id="myServiceLocator" class="com.boraji.tutorial.spring.MyService"/>
	<bean id="myService" factory-bean="myServiceLocator" factory-method="createService"/>
	
</beans>

MainApp.java

package com.boraji.tutorial.spring;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class MainApp {
   public static void main(String[] args) {
      ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
      MyService myService = context.getBean("myService", MyService.class);
      myService.doSomething();
   }

}

输出

Inside MyService private constructor.
Inside MyService private constructor.
Inside doSomething method

4、使用FactoryBean实例化bean

BeanFactory是spring容器的顶层接口,而这里要说的是FactoryBean,也是一个接口,这两个接口很容易混淆,FactoryBean可以让spring容器通过这个接口的实现来创建我们需要的bean对象。

FactoryBean接口源码:

public interface FactoryBean<T> {

    /**
     * 返回创建好的对象
     */
    @Nullable
    T getObject() throws Exception;

    /**
     * 返回需要创建的对象的类型
     */
    @Nullable
    Class<?> getObjectType();

    /**
    * bean是否是单例的
    **/
    default boolean isSingleton() {
        return true;
    }

}

接口中有3个方法,前2个方法需要我们去实现,getObject方法内部由开发者自己去实现对象的创建,然后将创建好的对象返回给Spring容器,getObjectType需要指定我们创建的bean的类型;最后一个方法isSingleton表示通过这个接口创建的对象是否是单例的,如果返回false,那么每次从容器中获取对象的时候都会调用这个接口的getObject() 去生成bean对象。

创建一个CarFactoryBean实现类

package com.myimooc.spring.simple.factorybean;

import org.springframework.beans.factory.FactoryBean;

/**
 * @author HP-susht
 * @create 2020-02-26 8:11
 * 自定义CarFactoryBean需要实现FactoryBean接口
 */
public class CarFactoryBean implements FactoryBean<Car> {

    private String brand;

    public void setBrand(String brand) {
        this.brand = brand;
    }

    //返回bean的对象
    @Override
    public Car getObject() throws Exception {
        return new Car(brand,600000);
    }

    //返回bean的类型
    @Override
    public Class<?> getObjectType() {
        return Car.class;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}

isSingleton:返回true,表示创建的对象是单例的,那么我们每次从容器中获取这个对象的时候都是同一个对象。

bean xml配置

<!-- 通过FactoryBean 创建Car对象 -->
<bean id="car" class="com.myimooc.spring.simple.factorybean.CarFactoryBean">
    <property name="brand" value="BMW"></property>
</bean>

Client代码

package com.myimooc.spring.simple.factorybean;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author HP-susht
 * @create 2020-02-26 8:16
 */
public class Main {
    public static void main(String[] args) {
        ApplicationContext context=new ClassPathXmlApplicationContext("spring-factory-bean.xml");

        Car car = (Car) context.getBean("car");
        System.out.println(car);

        //getBeanDefinitionNames用于获取容器中所有bean的名称
        for (String beanName : context.getBeanDefinitionNames()) {
            System.out.println(beanName + ":" + context.getBean(beanName));
        }

        System.out.println("--------------------------");
        //多次获取createByFactoryBean看看是否是同一个对象
        System.out.println("car:" + context.getBean("car"));
        System.out.println("car:" + context.getBean("car"));

    }
}


运行输出

信息: Loading XML bean definitions from class path resource [spring-factory-bean.xml]
execute getObject *************8
car:Car{brand='BMW', price=600000.0}
--------------------------
car:Car{brand='BMW', price=600000.0}
car:Car{brand='BMW', price=600000.0}

有3行输出的都是同一个CarFactoryBean,程序中通过getBean从spring容器中查找CarFactoryBean了3次,3次结果都是一样的,说明返回的都是同一个Car对象。

下面我们将CarFactoryBean中的isSingleton调整一下,返回false

@Override
public boolean isSingleton() {
    return false;
}

当这个方法返回false的时候,表示由这个FactoryBean创建的对象是多例的,那么我们每次从容器中getBean的时候都会去重新调用FactoryBean中的getObject方法获取一个新的对象。

再运行一下Client,观察输出结果:

信息: Loading XML bean definitions from class path resource [spring-factory-bean.xml]
execute getObject *************8
car:Car{brand='BMW', price=600000.0}
--------------------------
execute getObject *************8
car:Car{brand='BMW', price=600000.0}
execute getObject *************8
car:Car{brand='BMW', price=600000.0}

总结

spring容器提供了4种创建bean实例的方式,除了构造函数的方式,其他几种方式可以让我们手动去控制对象的创建。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值