手记

Spring 一二事(2)

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

风间影月

10实战 · 54手记 · 8推荐

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

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();
    }
2人推荐
随时随地看视频
慕课网APP