简介
- Spring是一个基于IOC和AOP的结构J2EE系统的框架
- 核心思想:IoC、AOP
- 简化企业开发,帮助分离对象之间的依赖关系
- spring能解决的问题
- 解耦应用程序,简化开发流程
- AOP支持
- 声明式事务
- 集成junit4
- 方便集成各种开源的优秀框架
- 降低JavaEE API的使用难度
程序的耦合
- 耦合:程序间的依赖关系
- 包括:类之间的依赖、方法间的依赖
- 解耦:降低程序键的依赖关系
- 实际开发中:应该做到编译期不依赖,运行时才依赖
- 解耦的思路:
- 1.使用反射来创建对象,而避免使用new关键字
- 2.通过读取配置文件来获取想要创建的对象全限定类名
- 例:注册数据库驱动时
DriverManager.registerDriver(new com.mysql.jdbc.Driver())//通过new创建 Class.forName("com.mysql.jdbc.Driver")//通过反射创建
Spring IOC
IOC 控制反转 是Spring的基础,Inversion Of Control 简单说就是创建对象由以前的程序员自己new 构造方法来调用,变成了交由Spring创建对象和保存对象
通过xml配置创建类对象步骤:
1.创建maven工程,在pom.xml文件配置spring的jar包坐标
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.8.RELEASE</version>
</dependency>
</dependencies>
2.在src/main/resources下创建spring的xml配置文件,配置bean对象
<?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
https://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 由spring创建管理对象 -->
<bean id="accountService" class="com.test.service.AccountService">
<!--给构造函数参数赋值-->
<constructor-arg name="username" value="zhansan"/>
<!--给类的成员变量age赋值,该类必须要有setAge()方法-->
<property name="age" value="10"/>
</bean>
</beans>
3.获取spring容器根据id获取bean对象
public static void main(String[] args) {
//获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("application.xml");
//根据id获取bean对象
AccountService accountService = ac.getBean("accountService", AccountService.class);
}