1.使用类构造器实现实例化(bean的自身构造器)
1 <bean id = "orderService" class="cn.itcast.OrderServiceBean"/>
2.使用静态工厂方法实现实例化
1 <bean id = "personService" class = "cn.itcast.OrderFactory" factory-method = "createOrder"/> 2 public class OrderFactory{ 3 private static OrderFactory orderFactory = new OrderFactory(); 4 private OrderFactory(); 5 public static OrderFactory createOrder(){ 6 return OrderFactory; 7 } 8 }
3.使用实例化工厂方法实现实例化(通过别的实体的bean)
1 <bean id = "personServiceFactory" class = "cn.itcast.service.OrderFactory"/> 2 <bean id = "persionService" factory-bean = "personServiceFactory" foctory-method = "createOrder"/> 3 public class OrderFactory{ 4 private static OrderService orderService = new OrderService(); 5 private OrderFactory(); 6 public static OrderService createOrderServiceBean{ 7 return OrderService; 8 } 9 10 }
我们通常把负责加载bean的BeanFactory或者ApplicationContext叫做Spring容器。两者都是通过xml配置文件加载bean,ApplicationContext和BeanFacotry相比,主要区别在于BeanFacotry是延迟加载,在调用getBean()的时候才实例化要get的bean。如果Bean的某一个属性无法注入,这时候才会抛出异常;而ApplicationContext默认,在初始化自身的时候就会对所有的bean做实例化,除非对bean设置lazy-init="true",这样有利于检查所依赖属性是否能注入。
另外,ApplicationContext提供了更多的扩展功能,如对要加载的资源文件的国际化’处理,对BeanPostProcessor的处理,
所以在J2EE应用中,通常情况下我们都选择使用ApplicationContext。不管是使用BeanFactory还是ApplicationContext,Spring 默认以singleton的方式初始化bean.
对于BeanFactory的初始化,通常用下面的代码:
1 ClassPathResource resource = new ClassPathResource("beans.xml"); 2 BeanFactory factory = new XmlBeanFactory(resource);
对于ApplicationContext的初始化,通常在web.xml中配置:
1 <context-param> 2 <param-name>contextConfigLocation</param-name> 3 <param-value> 4 classpath:conf/Appcontext.xml 5 </param-value> 6 </context-param> 7 <listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener>
或者
ApplicationContext context = new ClassPathXmlApplicationContext( new String[] {"applicationContext.xml", "applicationContext-part2.xml"});