Spring介绍
目录
Spring是什么
Spring是分层的Java SE/EE应用 full-stack轻量级开源框架,以IOC(控制反转)和AOP(面向切面编程)为内核
Spring的优势
通过Spring提供的IOC容器,可以将对象间的依赖关系交由Spring进行控制,避免编码造成的过度程序耦合,用户不必再为单例模式类,属性文件解析等这些底层的需求编写代码,可以更专注于上层的应用
Spring模块
Core:spring的核心功能: IOC容器, 解决对象创建及依赖关系
Web:Spring对web模块的支持。
DAO:Spring 对jdbc操作的支持
ORM:spring对orm框架的支持:
AOP:面向切面编程
JEE:spring对javaEE其他模块的支持
什么是耦合呢?我们又该如何解耦
耦合换个说法就是程序间的依赖:
包括了:类之间的依赖 及 程序间的依赖
我们用一段代码来给大家解释下
public class Jdbc {
public static void main(String[] args) throws SQLException, ClassNotFoundException {
//1.注册驱动 如果在pom文件中将mysql的驱动包注掉,程序将在编译期就报Error,这就是程序之间的耦合,
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Class.forName("com.mysql.jdbc.Driver"); //这就是对上一段代码的解耦 在驱动包注掉的情况下虽然还是报异常但是是程序运行时异常
//2.获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","root");
//3.获取操作数据库的欲处理对象
PreparedStatement statement = conn.prepareStatement("select * from user");
//4。执行sql,得到结果集
ResultSet rsList = statement.executeQuery();
//5.遍历结果集
while (rsList.next()){
System.out.println(rsList.getString("name"));
}
//6.释放资源
rsList.close();
statement.close();
conn.close();
}
}
代码一 :DriverManager.registerDriver(new com.mysql.jdbc.Driver());
代码二 :Class.forName("com.mysql.jdbc.Driver");
请注意 这两段代码都是在注册驱动 但是代码二却是对段代一码的解耦
我们可以测试一下将mysql的驱动包注掉
<!--<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>-->
这时候我们用代码一运行程序程序出现编译器错误
我们再试试代码二,运行得到结果
发现现在是运行时异常. 对!我们在实际开发中就应该做到编译期不依赖,运行时才依赖。
得到结论:要使用要使用反射来创建对象,避免使用new关键字
之前我在写程序的时候都是面向接口编程,通过BeanFactory来实现解耦
public class BeanFactory {
//定义一个properties对象
private static Properties properties;
//定义一个Map 用于存放我们要创建的容器,我们把它称为容器
private static Map<String,Object> beans;
//使用静态代码块为Properties对象赋值
static {
try {
//实例化对象
properties = new Properties();
//获取properties文件的流对象
InputStream in = BeanFactory.class.getClassLoader().getResourceAsStream("bean.properties");
properties.load(in);
//实例化容器
beans = new HashMap<String, Object>();
//取出配置文件中所有的key
Enumeration keys = properties.keys();
//遍历枚举
while (keys.hasMoreElements()){
//取出每个key
String key = keys.nextElement().toString();
//根据key获取value
String beanPath = properties.getProperty(key);
System.out.println("beanPath: "+beanPath);
//反射创建对象
Object value = Class.forName(beanPath).newInstance();
//把key和value存入容器
System.out.println("value: "+value);
beans.put(key,value);
}
} catch (Exception e) {
throw new ExceptionInInitializerError("初始化properties失败");
}
}
/**
* 根据Bean的名称获取bean对象 多例
* @param beanName
* @return
*
*
* 现在我们将其中一个类删除掉,再运行发现还是会异常,但这是正常的,不会像之前那样出现编译器错误
*
*/
// public static Object getBean(String beanName){
// Object bean = null;
// try {
// String beanPath = properties.getProperty(beanName);
// bean = Class.forName(beanPath).newInstance();
// //Class.forName()是动态加载类 newInstance()是对类进行实例化 每次都会调用默认的构造函数创建对象
// }catch (Exception e) {
// e.printStackTrace();
// }
// return bean;
// }
/**
* 根据bean的名称获取对象 单例
* @param beanName
* @return
*/
public static Object getBean(String beanName){
return beans.get(beanName);
}
}
## 配置文件bean.properties
accountService =com.mjw.service.impl.AccountServiceImpl
accountDao = com.mjw.dao.impl.AccountDaoImpl
Controller层和Service层通过BeanFactory来实现解耦,我们在BeanFactory中通过读取配置文件中的配置内容,来反射创建对象
这样我们就不用在Service层和Controller层使用new 关键字来创建对象了
public class AccountServiceImpl implements IAccountServicer {
/* private IAccountDao accountDao = new AccountDaoImpl();*/
private IAccountDao accountDao = (IAccountDao) BeanFactory.getBean("accountDao");
public void saveAccount() {
accountDao.saveAccount();
}
}
这种被动接收的方式获取对象的思想接收控制反转,它就是Spring框架的核心之一
控制反转
控制反转(Inversion of Control,英文缩写IOC)把创建对象的权力交给框架,是框架的重要特征,并非面向对象的专用术语。它包括依赖注入和依赖查找
明确ioc的作用
削减计算机程序的耦合(解除我们代码中的依赖关系)
Spring基于XML的IOC环境搭建
获取Spring的Ioc核心容器,并根据id获取bean对象
//1.获取核心容器对象
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据id获取bean对象
IAccountServicer as = (IAccountServicer) ac.getBean("accountService");
}
ApplicationContext的三个常用实现类
ClassPathXmlApplicationContext:加载类路径下的配置文件,配置文件必须在类路径下
FileSystemXmlApplicationContext:加载磁盘任意路径下的配置文件(必须有访问权限)
AnnotationfigAppLocationContext:用于读取注解创建容器
Spring依赖注入
依赖注入的数据有三类:
基本类型和String
其他bean类型,(在配置文件中或者注解配置过的bean)
复杂类型/集合类型
依赖注入的方式有三种:
第一种:使用构造函数提供
第二种:使用set方法提供
第三种:使用注解提供
一:构造函数注入
public class AccountServiceImpl implements IAccountServicer {
private String name;
private Integer age;
private Date birthday;
public AccountServiceImpl(String name,Integer age,Date birthday){
this.name = name;
this.age = age;
this.birthday = birthday;
}
@Override
public void saveAccount() {
System.out.println("service中的saveAccount方法执行了。。。"
+ name+","+age+","+birthday);
}
<?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来管理-->
<!--构造函数注入:
使用的标签:constructor-arg
标签中的属性:
name:给构造函数中指定名称的参数赋值
ref:用于指定其他的bean类型数据,它之的就是在spring的Ioc核心容器中出现的bean对象
-->
<bean id="accountService" class="mjw.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="2021_fc"/>
<constructor-arg name="age" value="22"/>
<constructor-arg name="birthday" ref="now"/>
</bean>
<!--配置一个日期对象-->
<bean id="now" class="java.util.Date"/>
</beans>标签:constructor-arg
-->
<bean id="accountService" class="mjw.service.impl.AccountServiceImpl">
<constructor-arg name="name" value="2021_fc"/>
<constructor-arg name="age" value="22"/>
<constructor-arg name="birthday" ref="now"/>
</bean>
<!--配置一个日期对象-->
<bean id="now" class="java.util.Date"/>
</beans>
测试对象注入成功
二:set方法注入
public class AccountServiceImpl implements IAccountServicer {
private String name;
private Integer age;
private Date birthday;
public void setName(String name) { this.name = name; }
public void setAge(Integer age) { this.age = age; }
public void setBirthday(Date birthday) { this.birthday = birthday; }
@Override
public void saveAccount() {
System.out.println("service中的saveAccount方法执行了。。。"
+ name+","+age+","+birthday);
}
}
<bean id="now" class="java.util.Date"/>
<!-- set方法注入-->
<bean id="accountService" class="mjw.service.impl.AccountServiceImpl">
<property name="name" value="2021_fc"/>
<property name="age" value="22"/>
<property name="birthday" ref="now"/>
</bean>
测试对象注入成功
set注入的优势和弊端
优势:创建对象时没有明确的限制,可以直接使用默认构造函数
弊端:如果有某个成员必须有值,则获取对象时有可能set方法没有执行
关于复杂类型注入
public class AccountServiceImpl2 implements IAccountServicer {
private String[] myStrs;
private List<String> myList;
private Set<String> mySet;
private Map<String,String> myMap;
private Properties myPro;
public void setMyStrs(String[] myStrs) { this.myStrs = myStrs; }
public void setMyList(List<String> myList) { this.myList = myList; }
public void setMySet(Set<String> mySet) { this.mySet = mySet; }
public void setMyMap(Map<String, String> myMap) { this.myMap = myMap; }
public void setMyPro(Properties myPro) { this.myPro = myPro; }
@Override
public void saveAccount() {}
}
<bean id="accountService" class="mjw.service.impl.AccountServiceImpl2">
<property name="myStrs">
<array>
<value>A</value></array></property>
<property name="myList">
<list>
<value>A</value></list></property>
<property name="mySet">
<set>
<value>A</value></set></property>
<property name="myMap">
<map>
<entry key="key" value="value"/></map></property>
<property name="myPro">
<props>
<prop key="key">value</prop></props></property>
</bean>
三:注解注入
配置基于注解的Ioc
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://www.springframework.org/schema/context/spring-context.xsd">
<!--告知spring在创建容器时要扫描的包,配置所需要的标签不在beans的约束中,
而是在一个名称为content名称空间和约束中-->
<context:component-scan base-package="mjw"/>
</beans>
@Autowired 自动按照类型注入
//dao层
@Repository("accountDao")
public class AccountDaoImpl implements IAccountDao {
@Override
public void saveAccount() {
System.out.println("执行了saveAccount方法...........");
}
}
//serbice层
@Service(value = "accountService")
public class AccountServiceImpl implements IAccountServicer {
@Autowired //自动按照类型注入
private IAccountDao accountDao;
@Override
public void saveAccount() {
accountDao.saveAccount();
}
}
@Autowired
作用:自动按照类型注入,只有容器中有唯一的bean对象类型和要注入的变量类型匹配,注入成功,如果ioc容器中没有任何bean的类型和要注入的变量类型匹配,则报错。