使用构造方法实例化bean
? ? eg:
? ? <bean id="bean1" name="code">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;}@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" 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.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd"><!-- id 表示你这个组件的名字,class表示组件类 --><bean id="bean1" 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 SpringHelloApi helloApi2 = context.getBean("bean2",HelloApi.class);helloApi2.sayHello();}