使用构造方法实例化bean

1,使用空构造器进行定义,使用这个方式,class属性指定的类必须有空构造器。
    eg:
    <bean id="bean1" class="cn.javass.spring.chapter2.HelloImpl2"/>

    2,使用有参数构造器进行定义,使用此种方式,可以使用<constructor-arg>标签指定构造器参数值,其中index表示位置,value表示常量值,也可以指定引用,指定引用使用ref来引用另外一个bean的定义。
package org.spring.chapter2.helloworld;

public interface HelloApi {

	void sayHello();
}

 package org.spring.chapter2.helloworld;

public class HelloImpl2 implements HelloApi {

	private String message;
	
	public HelloImpl2() {
		this.message="Hello World in Empty Constructor";
	}

	public HelloImpl2(String message) {
		this.message = message;
	}

	@Override
	public 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" xmlns:context="http://www.springframework.org/schema/context"
	xsi:schemaLocation="http://www.springframework.org/schema/beans   
	     				http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
						http://www.springframework.org/schema/context           
     					http://www.springframework.org/schema/context/spring-context-3.0.xsd">
	<!-- id 表示你这个组件的名字,class表示组件类 -->
	<bean id="bean1" class="org.spring.chapter2.helloworld.HelloImpl2"></bean>
	<bean id="bean2" class="org.spring.chapter2.helloworld.HelloImpl2">
	   <constructor-arg index="0" value="Hello Spring"></constructor-arg>
	</bean>
</beans>

  @Test

	public void testConstructor(){
		//1:读取配置文件实例化一个Ioc容器
		ApplicationContext context = new ClassPathXmlApplicationContext("org/spring/chapter2/helloworld/helloworld2.xml");
		
		//2:从容器中获取bean,注意此处是面向接口编程,而不是面向对象
		
		//3:调用空的构造函数,应该打印构造函数里面的那一句
		System.out.println("------------打印空构造函数-----------------------");
		HelloApi helloApi1 = context.getBean("bean1",HelloApi.class);
		helloApi1.sayHello();
		System.out.println("------------打印带参数的构造函数-----------------------");
		//4:调用有参数的构造函数,打印Hello Spring
		HelloApi helloApi2 = context.getBean("bean2",HelloApi.class);
		helloApi2.sayHello();
	}

猜你喜欢

转载自liuyiyou.iteye.com/blog/1614460
今日推荐