• 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();
    	}


  • 相关阅读:
    web-----------HTTP协议
    python基础作业------模拟实现一个ATM + 购物商城程序
    python--------进程与线程
    作业--用户输入数字0-100,判断成绩,用函数
    blog真正的首页
    blog首页视图
    让django完成翻译,迁移数据库模型
    创建Django博客的数据库模型
    创建blog APP
    在PyCharm上创建Django项目
  • 原文地址:https://www.cnblogs.com/raphael5200/p/5114744.html
Copyright © 2020-2023  润新知