使用Spring IoC进行设值注入
创建一个输出(hello,"内容" !)的类,通过Spring为内容赋值"Srping"字段
1、导入spring用到的jar包
Spring的jar包下载地址:https://repo.spring.io/webapp/#/home
2、创建helloSpring.java类
package cn.helloSpring;
public class HelloSpring {
// 定义who属性,该属性的值将通过Spring框架进行设置
private String who = null;
/**
* 定义打印方法,输出一句完整的问候。
*/
public void print() {
System.out.println("Hello," + this.getWho() + "!");
}
/**
* 获得 who。
*
* @return who
*/
public String getWho() {
return who;
}
/**
* 设置 who。
*
* @param who
*/
public void setWho(String who) {
this.who = who;
}
}
3、编写Spring 配置文件applicationContext.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-3.2.xsd">
<!-- 通过bean元素声明需要Spring创建的实例。该实例的类型通过class属性指定,并通过id属性为该实例指定一个名称,以便在程序中使用 -->
<bean id="helloSpring" class="cn.helloSpring.HelloSpring">
<!-- 指定被赋值的属性名 -->
<property name="who">
<!-- 赋值的内容 -->
<value>Spring</value>
</property>
</bean>
</beans>
4、编写test类进行测试:
package 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.helloSpring.HelloSpring;
class HelloSpringTest {
@Test
void test() {
// 通过ClassPathXmlApplicationContext实例化Spring的上下文
ApplicationContext context = new ClassPathXmlApplicationContext(
"applicationContext.xml");
// 通过ApplicationContext的getBean()方法,根据id来获取bean的实例
HelloSpring helloSpring = (HelloSpring) context.getBean("helloSpring");
// 执行print()方法
helloSpring.print();
}
}
运行结果及完整包路径: