继续浏览精彩内容
慕课网APP
程序员的梦工厂
打开
继续
感谢您的支持,我会继续努力的
赞赏金额会直接到老师账户
将二维码发送给自己后长按识别
微信支付
支付宝支付

Spring 一二事(2)

2018-05-10 11:40:193410浏览

风间影月

8实战 · 53手记 · 8推荐
TA的实战

静态工厂方法及实例工厂的使用:

applicationContext.xml:

<!-- factory-method 是指调用静态工厂方法 -->
    <bean id="helloWorld2" class="com.lee.spring002.createobject.method.HelloWorldFactory"
        factory-method="getInstance"></bean>

    <!-- 实例工厂 -->
    <bean id="helloWorldFactory"
        class="com.lee.spring002.createobject.method.HelloWorldFactory2"></bean>
    <!-- factory-bean 是一个工厂bean -->
    <bean id="helloWorld3" factory-bean="helloWorldFactory"
        factory-method="getInstance"></bean>

HelloWorldFactory.java

package com.lee.spring002.createobject.method;

import com.lee.spring001.createobject.HelloWorld;

public class HelloWorldFactory {

    public static HelloWorld getInstance() {
        return new HelloWorld();
    }
}

HelloWorldFactory2.java

package com.lee.spring002.createobject.method;

import com.lee.spring001.createobject.HelloWorld;

public class HelloWorldFactory2 {

    public HelloWorld getInstance() {
        return new HelloWorld();
    }
}

测试:

@Test
    public void testHelloWorld_StaticFactory() {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        HelloWorld hello = (HelloWorld)context.getBean("helloWorld2");
        hello.hello();
    }

    @Test
    public void testHelloWorld_InstanceFactory() {

        ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");

        HelloWorld hello = (HelloWorld)context.getBean("helloWorld3");
        hello.hello();
    }
打开App,阅读手记
“小礼物走一走,来慕课关注我”
赞赏支持
风间影月说
去围观
创业公司技术总监, 10年+开发和技术管理经验。SUN认证SCJP、PMP、MCP认证。主要从事后端技术和架构领域,有丰富的电商平台与物流平台核心系统的架构设计和开发经验。
发表评论
随时随地看视频慕课网APP