需求:
一个类包含另一个类。(ModelTest的一个字段为HelloWorld对象)
对ModelTest对象,注入一个HelloWorld对象
创建文件:
1.创建com.tutorialspoint包
2.创建HelloWorld类
3.创建MainAPP主类(void main)
4.创建Beans.xml
5.ModelTest类
代码:
HelloWorld.java
package com.tutorialspoint;
public class HelloWorld {
private String message;
public void setMessage(String message){
this.message = message;
}
public void getMessage(){
System.out.println("Your Message : " + message);
}
}
MainApp.java
package com.tutorialspoint;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class MainApp {
public static void main(String[] args) {
// TODO Auto-generated method stub
ApplicationContext context =
new ClassPathXmlApplicationContext("Beans.xml");
HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
obj.getMessage();
ModelTest model = (ModelTest) context.getBean("test");
model.getStr();
model.getHelloWorld();
}
}
Bean.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" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" 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/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<bean id="helloWorld" name="hello" class="com.tutorialspoint.HelloWorld">
<property name="message" value="Hello World!"/>
</bean>
<bean id="test" class="com.tutorialspoint.ModelTest">
<property name="str" value="Hello Str!"/>
<property name="helloWorld" ref="helloWorld"/>
</bean>
</beans>
ModelTest.java
package com.tutorialspoint;
public class ModelTest {
private String str;
private HelloWorld helloWorld;
public void setStr(String string){
this.str = string;
}
public void getStr(){
System.out.println("Your str : " + str);
}
public void setHelloWorld(HelloWorld helloworld){
this.helloWorld = helloworld;
}
public void getHelloWorld(){
helloWorld.getMessage();
}
}
运行结果
要点:
ref引用的可以是name也可以是id。