需求:

一个类包含另一个类。(ModelTest的一个字段为HelloWorld对象)
对ModelTest对象,注入一个HelloWorld对象

创建文件:

1.创建com.tutorialspoint包
2.创建HelloWorld类
3.创建MainAPP主类(void main)
4.创建Beans.xml
5.ModelTest类

代码:

HelloWorld.java

  1. package com.tutorialspoint;
  2. public class HelloWorld {
  3. private String message;
  4. public void setMessage(String message){
  5. this.message = message;
  6. }
  7. public void getMessage(){
  8. System.out.println("Your Message : " + message);
  9. }
  10. }

MainApp.java

  1. package com.tutorialspoint;
  2. import org.springframework.context.ApplicationContext;
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;
  4. public class MainApp {
  5. public static void main(String[] args) {
  6. // TODO Auto-generated method stub
  7. ApplicationContext context =
  8. new ClassPathXmlApplicationContext("Beans.xml");
  9. HelloWorld obj = (HelloWorld) context.getBean("helloWorld");
  10. obj.getMessage();
  11. ModelTest model = (ModelTest) context.getBean("test");
  12. model.getStr();
  13. model.getHelloWorld();
  14. }
  15. }

Bean.xml

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
  4. xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
  5. xsi:schemaLocation="
  6. http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
  8. http://www.springframework.org/schema/aop
  9. http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
  10. http://www.springframework.org/schema/tx
  11. http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
  12. http://www.springframework.org/schema/context
  13. http://www.springframework.org/schema/context/spring-context-3.0.xsd">
  14. <bean id="helloWorld" name="hello" class="com.tutorialspoint.HelloWorld">
  15. <property name="message" value="Hello World!"/>
  16. </bean>
  17. <bean id="test" class="com.tutorialspoint.ModelTest">
  18. <property name="str" value="Hello Str!"/>
  19. <property name="helloWorld" ref="helloWorld"/>
  20. </bean>
  21. </beans>

ModelTest.java

  1. package com.tutorialspoint;
  2. public class ModelTest {
  3. private String str;
  4. private HelloWorld helloWorld;
  5. public void setStr(String string){
  6. this.str = string;
  7. }
  8. public void getStr(){
  9. System.out.println("Your str : " + str);
  10. }
  11. public void setHelloWorld(HelloWorld helloworld){
  12. this.helloWorld = helloworld;
  13. }
  14. public void getHelloWorld(){
  15. helloWorld.getMessage();
  16. }
  17. }

运行结果

图片.png

要点:

ref引用的可以是name也可以是id。