Spring-IoC-DI-基于xml的依赖注入-使用set方法进行注入(案例一:注入基本数据类型属性)
案例一:注入基本数据类型属性
(1)创建类,定义属性和对应的set方法
//1.创建类 public class Book { //2.定义属性 private String bname; private String bauthor; //3.提供属性的set方法 public void setBname(String bname) { this.bname = bname; } public void setBauthor(String bauthor) { this.bauthor = bauthor; } @Override public String toString() { return "Book{" + "bname='" + bname + '\'' + ", bauthor='" + bauthor + '\'' + '}'; } }
(2)在spring配置文件中先配置对象创建,再配置属性注入
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 1.配置对象创建 -->
<bean id="book" class="com.orz.spring.test1.Book">
<!-- 2.属性注入 -->
<!-- 使用property完成属性注入
name:类里面的属性名称
value:向属性注入的值
-->
<property name="bauthor" value="金庸"></property>
<property name="bname" value="射雕英雄传"></property>
</bean>
</beans>
(3)测试
@Test public void test1() { //1.加载spring配置文件 ApplicationContext context=new ClassPathXmlApplicationContext("bean1.xml"); //2.获取配置文件的创建对象 Book book = context.getBean("book", Book.class); //3 System.out.println(book); }
(4)结果
Book{bname='射雕英雄传', bauthor='金庸'}