2008-04-29

使用构造方法创建Bean实例

关键字: spring
1,create a Message Interface:

package com.huyong.beans;

public interface Message {
public String showMessage();

}


2,create another Person Interface:

package com.huyong.beans;

public interface Person {
public void useMessage();

}


3,implement the Message's interface and the Person's interface

package com.huyong.beans;

public class MyPerson implements Person {
private Message message;

public void useMessage() {
System.out.println(message.showMessage());

}

/**
* @return the message
*/
public Message getMessage() {
return message;
}

/**
* @param message
* the message to set
*/
public void setMessage(Message message) {
this.message = message;
}

}


package com.huyong.beans;

public class MyMessage implements Message {

public String showMessage() {
return "these are my messages!";
}

}


4,the Main function:

package com.huyong.beans;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.ClassPathResource;

public class TestMain {

/**
* @param args
*/
public static void main(String[] args) {
ClassPathResource resource = new ClassPathResource(
"applicationContext.xml");
BeanFactory factory = new XmlBeanFactory(resource);
Person person = (Person) factory.getBean("myperson");
person.useMessage();

}

}



5,config applicationContext.xml:

<?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-2.0.xsd">
<bean id="myperson" class="com.huyong.beans.MyPerson">
<property name="message">
<ref local="mybean" />
</property>
</bean>
<bean id="mybean" class="com.huyong.beans.MyMessage"></bean>

</beans>
评论
发表评论

您还没有登录,请登录后发表评论