(5)Spring实例化Bean

来源:互联网 发布:怎样注册淘宝网店铺 编辑:程序博客网 时间:2024/06/13 03:40

例子:http://blog.csdn.net/shuair/article/details/78572449

添加一个实现类

package shuai.spring.study;public class HelloImpl2 implements HelloApi {private String message;public HelloImpl2() {this.message = "Hello World!2";}public HelloImpl2(String message) {this.message = message;}@Overridepublic void sayHello() {System.out.println(message);}}

配置文件

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://www.springframework.org/schema/beans        http://www.springframework.org/schema/beans/spring-beans.xsd">    <bean id="hello" class="shuai.spring.study.HelloImpl2"></bean>  </beans>

测试类

package shuai.spring.test;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import shuai.spring.study.HelloApi;public class HelloTest {@Testpublic void testHelloWorld() {@SuppressWarnings("resource")ApplicationContext context = new ClassPathXmlApplicationContext("HelloWorld.xml");HelloApi helloApi = context.getBean(HelloApi.class);helloApi.sayHello();}}
实例化bean

一、使用构造器

1、使用空构造器

<bean id="hello" class="shuai.spring.study.HelloImpl2"></bean>

测试输出:Hello World!2

2、使用有参构造

<bean id="hello" class="shuai.spring.study.HelloImpl2">    <constructor-arg index="0" value="Hello Spring!"/></bean>
使用<constructor-arg>标签指定参数值,index表示参数位置,value表示参数值

测试输出:Hello Spring!

二、使用使用静态工厂方法

添加一个类

package shuai.spring.study;public class HelloApiStaticFactory {// 工厂方法public static HelloApi newInstance(String message) {// 返回需要的Bean实例return new HelloImpl2(message);}}
配置文件

<bean id="hello" class="shuai.spring.study.HelloApiStaticFactory" factory-method="newInstance">    <constructor-arg index="0" value="静态工厂"/></bean>

使用class指定静态工厂方法所在的类,使用factory-method指定静态工厂方法(实例化bean的方法),如果方法有参数,像上面有参构造一样,使用constructor-arg。
输出结果:静态工厂

三、使用实例工厂

添加一个类

package shuai.spring.study;public class HelloApiInstanceFactory {public HelloApi newInstance(String message) {return new HelloImpl2(message);}}
配置文件

<bean id="beanInstanceFactory" class="shuai.spring.study.HelloApiInstanceFactory"/> <bean id="hello" factory-bean="beanInstanceFactory" factory-method="newInstance">    <constructor-arg index="0" value="实例工厂"/></bean>

要先为实例工厂配置一个bean,在我们要实例化的bean里面使用factory-bean引入实例工厂,这里不能使用class,其它的都一样。

输出结果:实例工厂

原创粉丝点击