spring中两种创建容器的方式和三种获取bean的方式

容器的不同决定了bean什么时候创建,而在bean里关于bean的配置方式不同,决定了bean怎么创建。

得到bean的容器有两种方式:

ApplicationContext----立即创建,也就是在ApplicationContext创建的时候就立马创建所有的bean。

ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");    //这一句执行完所有的bean都创建了
System.out.println(ac.getBean("customerService"));

BeanFactory----延迟创建,在用到bean的时候才会创建对应的bean.

Resource resource = new ClassPathResource("bean.xml");
BeanFactory factory = new XmlBeanFactory(resource );
factory.getBean("customerService");    //执行完这句之后,bean才会创建

配置bean的方式有三种:

<!--第一种,直接通过类名反射,调用无参构造方法创建对象-->
<bean id="customerService" class="com.dimples.service.impl.CustomerServiceImpl"></bean>
<!--第二种,通过静态工厂的方式获取bean对象-->
	<bean id="staticCustomerService" class="com.dimples.factory.StaticFactory" factory-method="getCustomer"/>
<!--通过实例工厂的模式获取bean对象-->
	<bean id="insFactory" class="com.dimples.factory.InstanceFactory"></bean>
	<bean id="insCustomer" factory-bean="insFactory" factory-method="getCustomer"/>

第二种的静态工厂类:

public class StaticFactory {
	public static CustomerServiceImpl getCustomer() {
		return new CustomerServiceImpl();
	}
}

第三种的实例工厂类:

public class InstanceFactory {
	public CustomerServiceImpl getCustomer() {
		return new CustomerServiceImpl();
	}
}

猜你喜欢

转载自blog.csdn.net/dimples_qian/article/details/81270337