SSM(十三)使用Spring IOC进行设值注入

本文详细介绍如何使用Spring框架实现控制反转,包括添加依赖jar包、编写JavaBean、配置XML及获取实例的过程,帮助读者掌握Spring的基本操作。

一、案例:如何使用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属性:指定多个别名,名字之间使用逗号,分号或空格进行分隔

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值