Spring环境搭建与IOC案例

3 篇文章 0 订阅

Spring环境搭建与IOC案例


一、 搭建Spring环境

1. 创建Java项目

file -> new -> java project -> 输入project name -> finish。

2. 导入Spring相关jar包

Spring百度云资源:
链接:https://pan.baidu.com/s/14UxoW2l3r280H8TPi50Fpw 
提取码:1mts 
复制这段内容后打开百度网盘手机App,操作更方便哦

commons-logging.jar百度云资源:
链接:https://pan.baidu.com/s/17bXzmbFwEVss9hqrhJyVOg 
提取码:vuah 
复制这段内容后打开百度网盘手机App,操作更方便哦

解压上面的Spring压缩包,将commons-logging.jar以及Spring四个核心jar包(beans、core、context、expression)拷贝到项目src目录下,然后右击这五个jar包 -> build path -> add to build path。

3. 创建bean.xml配置文件

创建com.au.test包,在里面创建bean.xml文件,写入如下内容:

<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">
</beans>

二、 IOC案例

1. IOC简介

IOC(Inverse of Control)反转控制的概念,就是将原本在程序中手动创建对象的控制权,交由Spring框架管理,简单说,就是创建对象控制权被反转到了Spring框架。

2. 使用Spring与不用Spring的区别

a. 在com.au.service包下创建StudentService.java类
package com.au.service;

public class StudentService {
	public void addStudent() {
		System.out.println("addStudent()...");
	}
}
b. 在bean.xml文件添加如下内容
<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配置 -->
	<bean id="studentServiceId" class="com.au.service.StudentService"></bean>

</beans>
c. 创建测试类Main.java
package com.au.test;

import org.junit.Test; // 注意导入junit相关jar包
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.au.service.StudentService;

public class Main {

	@Test
	public void test01() {
		// 原始方法调用addStudent方法,先new对象,然后通过对象调用方法
		StudentService service = new StudentService();
		service.addStudent();
	}

	@Test
	public void test02() {
		// Spring IOC,不用自己new对象,通过Spring来实现调用addStudent方法,底层使用了工厂模式+反射
		String xmlPath = "com/au/test/bean.xml";
		ApplicationContext ac = new ClassPathXmlApplicationContext(xmlPath);
		StudentService service = (StudentService) ac.getBean("studentServiceId");
		service.addStudent();
	}

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值