一、案例:如何使用Spring实现控制反转
1. 编写HelloSpring类,输出“Hello,Spring!”
2. 字符串“Spring”通过Spring注入到HelloSpring类中。
二、分析步骤
1. 添加Spring所依赖的jar包到项目中
打开Spring官网,repo.spring.io,在search栏中输入需要的jar包:spring-framework-3.2.13
在一系列结果中,选择:spring-framework-3.2.13.RELEASE-dist.zip
引入jar包:commons-logging-1.2.jar;log4j-1.2.17.jar;spring-beans-3.2.13.RELEASE.jar;
spring-context-3.2.13.RELEASE.jar;spring-core-3.2.13.RELEASE.jar;spring-expression-3.2.13.RELEASE.jar
2. 编写JavaBean
package cn.springdemo;
public class HelloSpring {
//定义变量who,它的值通过Spring框架进行注入
private String who;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
/**
* 定义打印方法,输出一句完整的问候
*/
public void print() {
System.out.println("Hello, " + this.getWho() + "!");
}
}
3. 编写配置文件
<?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元素声明Spring创建的对象实例,id属性指定对象的唯一标识符,方便程序的使用,class属性指定被声明的实例对应的类 -->
<bean id="helloSpring" class="cn.springdemo.HelloSpring">
<!-- 指定被赋值的属性名 -->
<!-- 注意:name的值和set后面的对应,不是和属性值名称对应 -->
<property name="who">
<!-- 赋值的内容 -->
<value>Spring</value>
</property>
</bean>
</beans>
4. 编写代码获取HelloSpring实例
package cn.test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.springdemo.HelloSpring;
class HelloSpringTest {
@Test
void test() {
//1.首先读取Spring配置文件
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
//2.通过ApplicationContext对象的getBean("id值"),获取对应类的对象,因为此方法返回Object类型,需要进行强制类型转换
HelloSpring helloSpring = (HelloSpring)applicationContext.getBean("helloSpring");
helloSpring.print();
}
}
三、经验
设值注入
使用<bean>元素定义一个组件
id属性:指定一个用来访问的唯一名称
name属性:指定多个别名,名字之间使用逗号,分号或空格进行分隔