zoukankan      html  css  js  c++  java
  • Spring、实例化Bean的三种方法

    1、使用类构造器进行实例化

    <bean id="personIService" class="cn.server.impl.PersonServiceImpl" />

    测试代码:

    @Test
    	public void test() {
    		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    		PersonIService personIService=(PersonIService)ac.getBean("personIService");
    		personIService.helloSpring();
    	}

    2、使用静态工厂实例化

    public class BeanFactory {
    	public static PersonServiceImpl createPersonServiceImpl(){
    		return new PersonServiceImpl();
    	}
    }
    <bean id="personIService2" class="cn.BeanFactory" factory-method="createPersonServiceImpl" />


    测试代码:

    	@Test
    	public void test3() {
    		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    		PersonIService personIService=(PersonIService)ac.getBean("personIService2");
    		personIService.helloSpring();
    	}

    3、使用实例化工厂实例化

    public class BeanFactory {
    	public PersonServiceImpl createPersonServiceImpl2(){
    		return new PersonServiceImpl();
    	}
    }
    	<bean id="beanFactory" class="cn.BeanFactory"/>
    	<bean id="personIService3" factory-bean="beanFactory"  factory-method="createPersonServiceImpl2" />


    测试代码:

    	@Test
    	public void test4() {
    		ApplicationContext ac = new ClassPathXmlApplicationContext("beans.xml");
    		PersonIService personIService=(PersonIService)ac.getBean("personIService3");
    		personIService.helloSpring();
    	}


  • 相关阅读:
    [转载]Centos7.x下环境搭建(一)--yum方式安装mysql5.7
    树上分治
    [SPOJ2666]QTREE4
    [SPOJ375]QTREE
    [SPOJ1825]FTOUR2
    [POJ1741]Tree
    [LG-P5350]序列
    [COCI 2014/2015 #3]KAMIONI
    [SHOI2014]神奇化合物
    [GXOI/GZOI2019]旧词
  • 原文地址:https://www.cnblogs.com/raphael5200/p/5114744.html
Copyright © 2011-2022 走看看