Book.java
1 package cn.com.xf; 2 3 public class Book { 4 private String name; 5 private double price; 6 public String getName() { 7 return name; 8 } 9 public void setName(String name) { 10 this.name = name; 11 } 12 @Override 13 public String toString() { 14 return "Book [name=" + name + ", price=" + price + "]"; 15 } 16 public double getPrice() { 17 return price; 18 } 19 public void setPrice(double price) { 20 this.price = price; 21 } 22 }
Person.java
注意:@Resource(name="book")位置
1 package cn.com.xf; 2 3 import javax.annotation.Resource; 4 5 public class Person { 6 private String address; 7 @Resource(name="book") 8 private Book book; 9 public String getAddress() { 10 return address; 11 } 12 public void setAddress(String address) { 13 this.address = address; 14 } 15 @Override 16 public String toString() { 17 return "Person [address=" + address + ", book=" + book + "]"; 18 } 19 public Book getBook() { 20 return book; 21 } 22 public void setBook(Book book) { 23 this.book = book; 24 } 25 }
Spring配置文件:声明 org.springframework.context.annotation.CommonAnnotationBeanPostProcessor 类
<?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.xsd"> <bean id="book" class="cn.com.xf.Book"> <property name="name" value="java系列丛书"></property> <property name="price" value="34.56"></property> </bean> <bean id="person" class="cn.com.xf.Person"> <property name="address" value="河南省淅县"></property> </bean> <bean class="org.springframework.context.annotation.CommonAnnotationBeanPostProcessor"> </bean> </beans>
测试类:正确返回结果.
1 package cn.com.xf; 2 3 import org.springframework.context.ConfigurableApplicationContext; 4 import org.springframework.context.support.ClassPathXmlApplicationContext; 5 6 public class MainTest { 7 8 public static void main(String[] args) { 9 ConfigurableApplicationContext ctx=new ClassPathXmlApplicationContext("applicationContext.xml"); 10 Person p=(Person) ctx.getBean("person"); 11 System.out.println(p); 12 ctx.close(); 13 } 14 }
时间: 2024-12-29 23:23:16