Bean的实例化方式,有三种:默认构造,静态工厂,实例工厂
默认构造:
<bean id = “userServiceId” class= “全限定类名”></bean>
此前的都是默认构造。
静态工厂:主要是由工厂对bean实例的创建,由于是静态工厂,所以工厂类中的所有方法都是静态的,在使用Spring之前:都是通过静态工厂的静态方法对实例进行创建,如下:
UserService userService = MyBeanFactory.createService();
在使用Spring之后,我们要把创建bean的任务交给Spring,
即为:
String xmlPath = “…/…/…”;
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“xmlPath”);
UserService userService = applicationContext.getBean(“userSreviceId”, UserService.class);
要能这样写,首先我们要进行xml文件的配置,因为是静态工厂方式,所以配置文件自然与默认配置有所区别:
<bean id = “userServiceId” class = “静态工厂全限定类名(…MyBeanFactory)” factory-method = “createService”></bean>
实例工厂:主要是由工厂的实例对相应bean实例进行创建,由于是实例工厂,所以工厂类中的方法都不是静态的,在使用Spring之前,都是通过实例工厂的实例对象调用其方法对相应bean实例进行创建的,如下:
MyBeanFactory myBeanFactory = new MyBeanFactory();
UserService userService = myBeanFactory.createService();
在使用Spring之后,同样我们把创建bean的任务交给Spring。
String xmlPath = “”;
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(“xmlPath”);
UserService userService = applicationContext.getBean(“userSreviceId”, UserService.class);
由于是实例工厂的方式,所以配置文件又有所差别:
① 创建工厂实例
<bean id = “myBeanFactoryId” class = “全限定类名”></bean>
② 获得userService
<bean id = “userServiceId” factory-bean = “myBeanFactoryId” factory-method = “createService”></bean>