Spring概述
Spring是由Rod Johnson组织开发的一个分层的Java SE/EE一站式轻量级开源框架。它最核心的理念是控制反转和面向切面编程
Spring框架的优点
非倾入式设计
降低耦合性,方便开发
支持AOP编程
支持声明式事物
方便程序的测试
方便基层各种优秀框架
降低java EE API的使用难度
Spring的体系结构
重点掌握Core Container 和 Test
核心容器Core Container
1.Beans模块
Beans模块提供了BeanFactory类,是工厂模式的经典实现,Beans模块的主要作用是创建和管理Bean对象
2.Core模块
Core模块提供了Spring框架的基本组成部分,包括Ioc和依赖注入(DI)功能,提供基本的运行
3.Context模块
Context模块构建于Beans模块和Core模块的基础上,它可以通过ApplicationContext接口提供上下文信息,是取Bean的媒介
4.SpEL模块
SpEL是一个在程序运行时支持操作对象图的表达式语言
Test
Test模块提供了对程序单元测试和集成测试的支持
Spring的依赖包
<!--Spring的依赖包commons-logging-->
控制反转与依赖注入
控制反转是面向对象编程中的一个设计原则,用于降低程序代码之间的耦合度
对象实例不再由调用者来创建,而是由Spring的IoC容器来创建,IoC容器会负责控制程序之间的关系,而不是由调用者的程序代码直接控制,控制权转移到了IoC容器,控制发生了反转
依赖注入是指在使用Spring框架构建对象时,动态地将其所依赖的对象注入到Bean组件中;通过构造方法或setter方法注入
构造方法注入
package com.itheima;
public class User1{
private int id;
private String password;
private String name;
//有参构造方法
public User1(int id, String name, String password){
this.id = id;
this.name = name;
this.password = password;
}
public String toString(){
return "id="+id+",name="+name+",password="+password;
}
}
<bean id="user1" class="com.itheima.User1">
<constructor-arg name="id" value="1"></constructor-arg>
<constructor-arg name="name" value="张三"></constructor-arg>
<constructor-arg name="password" value="123"></constructor-arg>
</bean>
Setter方法注入
package com.itheima;
public class User2{
private int id;
private String name;
private String password;
public void setId(int id){
this.id = id;
}
public void setName(String name){
this.name = name;
}
public void setPassword(String password){
this.password = password;
}
public String toString(){
return "id="+id+",name="+name+",password="+"password";
}
}
<bean id="User2" class="com.itheima.User2">
<property name="id" value="2"></property>
<property name="name" value="李四"></property>
<property name="password" value="456"></property>
</bean>