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();
}
}