zoukankan      html  css  js  c++  java
  • spring实例化bean的方式

    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"});

      

    肆虐的海水
  • 相关阅读:
    HDU3145 Max Sum of Max-K-sub-sequence (单调队列模板)
    AcWing1088 旅行问题(单调队列)
    POJ1821 Fence(单调队列)
    POJ1742 Coins(多重背包+二进制优化)
    AcWing217 绿豆蛙的归宿(期望)
    BZOJ.2134.[国家集训队]单选错位(概率 递推)
    洛谷.3805.[模板]manacher算法
    Codeforces.280C.Game on Tree(期望)
    BZOJ.2521.[SHOI2010]最小生成树(最小割ISAP/Dinic)
    洛谷.4172.[WC2006]水管局长(LCT Kruskal)
  • 原文地址:https://www.cnblogs.com/ckysea/p/4526630.html
Copyright © 2011-2022 走看看