随着企业级系统的 大规模:用户数量多、数据规模大、功能众多、 性能和安全要求高、 业务复杂、灵活应变
java技术如何应对?所以spring出现了。
首先我们先来看一下Spring框架的一些知识点,通过下边这张图来总括一下:
Spring是轻量级框架, Java EE的春天,当前主流框架
目标:使现有技术更加易用,推进编码最佳实践
内容:IoC容器、AOP实现、数据访问支持、简化JDBC/ORM 框架、声明式事务、Web集成
1.先看一下下面的图,主要包括了Spring自身的功能。还有可以和其框架结合的一些框架,通过这图可以看出,Spring框架和其他框架的集成能力是非常强的。
2.Spring是一个轻量级的IOC和AOP容器框架:
1)轻量级:占用资源不是很多,低侵入性。
2)IOC:控制反转(Inversion of Control),是一个重要的面向对象编程的法则来削减计算机程序的耦合问题,也是轻量级的Spring框架的核心,beans。
说的是创建对象实例的控制权从代码控制剥离到IOC容器(spring容器)控制,实际就是你在xml文件控制,侧重于原理。
3)AOP::一种面向横切面编程的思想方式,可以进行功能性扩展。
3.spring基本jar包
4.spring的小案例
a.导入jar包
b.创建一个类:HelloSpring
c.配置文件:applicationContext.xml
d.单测
HelloSpring
public class HelloSpring {
private String who=null;
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public void print(){
System.out.println("Hello," +this.getWho());
}
}
<?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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd">
<!--1.HelloSpring-->
<bean id="helloSpring" class="cn.happy.entity.HelloSpring" >
<property name="who">
<value>Spring</value>
</property>
</bean>
</beans>
测试类:
public class HelloSpringTest {
@Test
public void helloSpringTest(){
ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
HelloSpring hs= (HelloSpring) context.getBean("helloSpring");
hs.print();
}
}
ApplicationContext来用才对象来加载Spring配置文件,会在加载时解析配置文件,创建对象,而不是在getBean时创建。其实,ApplicationContext接口继承了BeanFactory,所以具备BeanFactory所有功能,同时增加扩展的功能,例如加载资源配置文件,国际化支持等!
5.Sping框架的优缺点:
优点:
- 轻量级的容器框架,没有侵入性
- IoC更加容易组合对象之间的关系,通过面向接口进行编程,可以低耦合开发。
- 易于本地测试(Junit单元测试,不用部署服务器)
- AOP可以更加容易的进行功能扩展,遵循OCP开发原则。
- Spring默认对象的创建为单例的,我们不需要再使用单例的设计模式来开发单体类。
- Spring的集成很强大,另外可以对其他框架的配置进行一元化管理。
- Spring的声明式事务的方便使用。
缺点:
自我感觉是所有框架共有的,就是开发对设计要求较高,集成测试麻烦,对框架有一定的依赖性。