Spring5 基于xml方式注入属性的三种方式
1、使用set方法进行注入
1.1 maven依赖
<dependencies>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.1.1</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<version>RELEASE</version>
<scope>test</scope>
</dependency>
</dependencies>
1.2 创建实体类
package com.aiguigu.spring5;
public class Book {
private String bookName;
private String bookAuthor;
public void setBookName(String bookName) {
this.bookName = bookName;
}
public void setBookAuthor(String bookAuthor) {
this.bookAuthor = bookAuthor;
}
public void bookPrint() {
System.out.println(bookName + "::" + bookAuthor);
}
}
1.3 配置xml文件
<bean id="book" class="com.aiguigu.spring5.Book">
<property name="bookName" value="平凡的世界"></property>
<property name="bookAuthor" value="路遥"></property>
</bean>
1.4 测试类编写
@Test
public void testBook() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
Book book = applicationContext.getBean("book",Book.class);
System.out.println(book);
book.bookPrint();
}
1.5 结果输出
2、使用有参构造进行注入
2.1 maven依赖
2.2 创建实体类
package com.aiguigu.spring5;
public class Orders {
private String orderName;
public Orders(String orderName) {
this.orderName = orderName;
}
public void orderPrint() {
System.out.println(orderName);
}
}
2.3 配置xml文件
<bean id="order" class="com.aiguigu.spring5.Orders">
<constructor-arg name="orderName" value="电脑"></constructor-arg>
</bean>
2.4 测试类编写
下面展示一些 内联代码片
。
@Test
public void testOrder() {
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean1.xml");
Orders order = applicationContext.getBean("order", Orders.class);
System.out.println(order);
order.orderPrint();
}