您的位置:首页 > 编程语言 > Java开发

Spring 一二事(2)

2016-03-22 10:50 417 查看
静态工厂方法及实例工厂的使用:

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


github地址:https://github.com/leechenxiang/maven-spring001-helloworld
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: