2.Bean管理-注入属性
Book类
package Spring5;
public class Book {
private String bookName;
private String authorName;
public Book() {
}
public Book(String bookName, String authorName) {
this.bookName = bookName;
this.authorName = authorName;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getAuthorName() {
return authorName;
}
public void setAuthorName(String authorName) {
this.authorName = authorName;
}
public void show(){
System.out.println(bookName+" "+authorName);
}
}
Order类
package Spring5;
public class Order {
private String orderName;
private String orderAddress;
public Order(){}
public Order(String orderName, String orderAddress) {
this.orderName = orderName;
this.orderAddress = orderAddress;
}
public void show(){
System.out.println(orderName+" "+orderAddress);
}
}
bean1.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.xsd">
<bean id="user" class="Spring5.User">
</bean>
<!--通过set方法注入属性-->
<bean id="book" class="Spring5.Book">
<property name="authorName" value="吴承恩"></property>
<property name="bookName" value="西游记"></property>
</bean>
<!-- 通过有参构造注入属性-->
<bean id="order" class="Spring5.Order">
<constructor-arg name="orderName" value="电脑"></constructor-arg>
<constructor-arg index="1" value="大连"></constructor-arg>
</bean>
</beans>
Test类
public class TEST {
@Test
public void testBook(){
//实现bean容器
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
//获取配置创建的对象
Book book =context.getBean("book",Book.class);
System.out.println(book);
book.show();
}
@Test
public void testOrder(){
//实现bean容器
ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml");
//获取配置创建的对象
Order order =context.getBean("order",Order.class);
System.out.println(order);
order.show();
}
}
testBook测试结果
Spring5.Book@327514f
西游记 吴承恩
testOrder测试结果
Spring5.Order@327514f
电脑 大连