Spring框架
1、Spring框架的概述
Spring是一个开源框架
Spring是在2003年兴起的一个轻量级的Java开发框架,由Rod Johnson在其著作Expert One-on-One J2EE Development and Design中阐述的部分理念和原型衍生而来。
是为了解决企业应用开发的复杂性而创建的,框架的主要优势之一就是其分层架构,分层架构允许使用者选择使用哪一个组件同时为J2EE应用程序开发通过集成的框架。
Spring使用基本的JavaBean来完成以前只可能由EJB完成的事情。然而,Spring的用途不仅限于服务器端的开发,从简单性、可测试性、和松耦合的角度而言,任何Java应用都可以从Spring收益
Spring的核心是控制反转(IOC)和面向切面(AOP)简单来说,Spring是一个分层的JavaSE/EEfull-stack(一站式)轻量级开源框架
EE开发分层三层结构
WEB层 ---SpringMVC
业务层 ---Bean管理(IOC)
持久层 --- Spring的JDBC模版,ORM模版用于整合其他的持久层框架
Spring框架的特点
1、学习的原因
方便解耦,简化开发
Spring就是一个大工厂,可以将所有对象创建和依赖关系维护,交给Spring管理
AOP编程的支持
Spring提供面向切面编程,可以方便的实现对程序进行权限拦截,运行监控等功能
声明式事务的支持
只需要通过配置就可以完成对事务的管理,而无需手动编程
方便程序的调试
Spring对Junit4支持,可以通过注解方便的测试Spring程序
方便集成各种优秀框架
Spring不排斥各种优秀的开源框架,其内部提供了对各种优秀框架(Struts2、Hibernate、MyBatis、Quartz等)的直接支持
降低JavaEE API的使用难度
Spring对JavaEE开发中非常难用的一些API(JDBC、JavaMail、远程调用等)都提供了封装,使这些API应用难度大大降低
2、Spring框架的版本
Spring3.x和Spring4.x等的版本
IOC核心功能入门
1、IOC的功能
ioc inverse of control,控制反转,将对象的创建权反转给spring
使用ioc可以解决程序耦合性高的问题
2、下载Spring框架包
官网http://spring.io/
下载 http://repo.springsource.org/libs-release-local/org/springframework/spring 目录结构:
docs --API和开发规范
libs --jar包和源码
schema--约束
log4j是logging的实现
3、创建JavaWEB项目,引入Spring的开发包
引入Spring框架IoC核心功能需要的具体的jar包
IOC功能根据体系结构图 只需要引入
Beans/core/context/Expression Language
Spring框架也需要引入日志相关的包
commons.logging-1.1.1.jar
log4j的jar包
log4j-1.2.15.jar
4、创建对应的包结构,编写Java类 以后使用Spring框架做开发,都需要来编写接口和实现类
my.demo1
UserService 接口
UserServiceImpl 具体的实现类
5、把UserServiceImpl实现类的创建交给Spring框架来管理,需要创建Spring框架的配置文件,完成配置
在src目录下创建applicationContext.xml配置文件,名称可以是任意的,但是一般会使用默认名称
引入spring的约束,需要先找到具体的约束头信息
spring-framework-4.2.4.RELEASE\docs\spring-framework-reference\html\xsd-configuration.html
具体的约束
<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>
完成UserService的配置
<bean id="userService" class="my.demo2.UserServiceImpl"/>
6、采用Spring框架的工厂方式来获取到UserService接口的具体实现类
public void run3() {
//创建工厂,加载核心配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从工厂当中获取到对象
UserService us = (UserService) ac.getBean("userService");
//调用对象的方法执行
us.sayHello();
}
Spring框架中的工厂
1、ApplicationContext接口
使用ApplicationContext工厂的接口,使用该接口可以获取到具体的Bean对象
该接口下有两个具体的实现类
ClassPathXmlApplicationContext 加载类路径下的Spring配置文件
FileSystemXmlApplicationContext 加载本地磁盘下的Spring配置文件
2、BeanFactory工厂(是Spring框架早期的创建Bean对象的工厂接口)
使用BeanFactory接口也可以获取到Bean对象
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
UserService us = (UserService) factory.getBean("userService");
us.sayHello();
BeanFactory和ApplicationContext的区别
BeanFactory BeanFactory采取延迟加载,第一次getBean时才会初始化Bean
ApplicationContext 在加载applicationContext.xml时候就会创建具体的Bean对象的实例,还提供了一些其他的功能
事件传递
Bean自动装配
各种不同应用层的Context实现
Spring框架编写XML的提示
1、先复制http://www.springframework.org/schema/beans/spring-beans.xsd
2、搜索XML Catalog -》ADD按钮
3、先选择Location的Schema的约束地址
spring-framework-4.2.4.RELEASE\schema\beans\spring-beans-4.2.xsd
4、Key type 选择 Schema location
5、Key把http://www.springframework.org/schema/beans/spring-beans.xsd复制上
Spring框架中<bean>标签的配置
1、id属性和name属性的区别
id Bean起个名字,在约束中采用ID的约束,唯一
取值要求:必须以字母开头,可以使用字母、数字、连字符、下划线、句号、冒号 id:不能出现特殊字符
name bean起个名字,没有采用ID的约束
取值要求:name:出现特殊字符,如果<bean>没有id的话,name可以当作id使用
Spring框架在整合struts1框架的时候,Struts1的框架的访问路径是以/开头的 例如/bookAction
2、class属性 Bean对象的全路径
3、scope属性 scope属性代表Bean的作用范围
singleton 单例(默认值)
prototype 多例,在Spring框架整合Struts2框架的时候,Action类也需要交给Spring做管理,配置把Action类配置成多例
request 应用在Web项目中,每次Http请求都会创建一个新的Bean
session 应用在Web项目中,同一个HttpSession共享一个Bean
globalsession 应用在web项目中,多服务期间的session
4、Bean对象的创建和销毁的两个属性配置
Spring初始化bean或销毁Bean时,有时需要一些处理工作,因此spring可以在创建和拆卸bean的时候调用bean的两个生命周期方法
init-method 当bean被载入到容器的时候调用init-method属性指定的方法
destory-method 当bean从容器中删除的时候调用destory-method属性指定的方法
想查看destory-method的效果,有如下条件
scope=singleton
web容器中会自动调用,但是main函数或测试用例需要手动调用(需要使用ClassPathXmlApplicationContext的close()方法)
依赖注入(DI)
1、IoC和DI的概念
IOC Inverse of Control 控制反转,将对象的创建权反转给Spring
DI Dependency Injection 依赖注入,在Spring框架负责创建Bean对象时,动态的将依赖对象注入到Bean组件中
2、DI(依赖注入)
如果UserServiceImpl的实现类中有一个属性,那么使用Spring框架的IOC功能时,可以通过依赖注入把属性的值传入进来
<bean id="userService" class="my.demo2.UserServiceImpl" >
<property name="name" value="小弟"></property>
</bean>
Spring框架的属性注入
1、对于类成员变量,常用的注入方式有两种
构造函数注入
属性setter方法注入
2、在Spring框架中提供了前两种的属性注入的方式
1、构造方法的注入方式,两步
编写java类,提供构造方法
有参构造方法和toString
编写配置文件
<bean id="car1" class="my.demo4.Car1">
<!-- <constructor-arg name="cname" value="板车"></constructor-arg>
<constructor-arg name="price" value="2"></constructor-arg> -->
<constructor-arg index="0" value="大奔"></constructor-arg>
<constructor-arg index="1" value="33"></constructor-arg>
</bean>
2、属性的setter方法的注入方式
编写Java的类,提供属性和对应的set方法即可
编写配置文件
3、如果Java类的属性是另一个Java的类,那么需要:
<property name="name" rel="具体的Bean的ID或者name的值"
<bean id="person" class="my.demo4.Person">
<constructor-arg name="pname" value="小弟"></constructor-arg>
<constructor-arg name="car1" ref="car1"></constructor-arg>
</bean>
2.5版本提供 p名称框架的注入
1、引入p名称空间
在schema的名称空间中加入该行xmlns:p="http://www.springframework.org/schema/p"
2、使用p名称框架的语法
p:属性名=""
p:属性名-ref=""
3、测试
<bean id="person" class="my.demo4.Person" p:pname="小风" p:car2-ref="car2"/>
3.0提供 SpEL注入方式
1、SpEL Spring Expression Language是Spring的表达式语言
2、语法
#(SpEL)
3、例如:
<bean id="car2" class="my.demo4.Car2">
<property name="cname" value="#{'福特'}"></property>
<property name="car2" value="#{car2}"></property>
</bean>
4、还支持调用类中的属性或者方法
定义类和方法
<property name="car2" value="#{car2.getCarname}"></property>
数组,集合(List,Set,Map)Properties等的注入
1、如果是数组或者List结合,注入配置文件的方式是一样的
<property name="arrs" >
<list>
<value>小弟</value>
<value>小弟1</value>
<value>小弟2</value>
</list>
</property>
2、如果是Set集合
<property name="set" >
<set>
<value>小弟</value>
<value>小弟1</value>
<value>小弟2</value>
</set>
</property>
3、如果是Map集合
<property name="map" >
<map>
<entry key="aaa" value="啦啦啦"></entry>
<entry key="bbb" value="Wllala"></entry>
</map>
</property>
4、如果是properties属性文件的方式
<property name="pro">
<props>
<prop key="username">root</prop>
<prop key="password">123</prop>
</props>
</property>
配置文件分开管理
1、在src的目录下多创建一个配置文件,有两个核心的配置文件,那么加载这两个配置文件的方式有两种
主配置文件中包含其他的配置文件
<import resource="applicationContext2.xml"/>
工厂创建的时候直接加载多个配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml","applicationContext2.xml");
整合Web(初步)
1、创建JavaWeb项目,引入Spring的开发包,编写具体的类和方法
环境搭建好后,启动服务器来测试项目,发送每访问一次都会加载一次配置文件,这样效率很低
2、解决上面的问题
将工厂创建好了以后放入ServletContext域中,使用工厂的时候,从ServletContext中获取
SerletContextListener,用来监听ServletContext对象的创建和销毁的监听器
当ServletContext对象创建的时候,创建工厂,将工厂存入到ServletContext
3、Spring整合Web项目
引入spring0web-4.2.4.RELEASE.jar包
配置监听器
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
4、修改servlet的代码
从ServletContext中获取工厂
ServletContext servletContext = ServletActionContext.getServletContext();
//使用web工厂的方式
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
CustomerService cs = (CustomerService) context.getBean("customerService");
cs.save();
applicationContext.xml
<?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:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 配置客户的业务层 -->
<bean id="customerService" class="my.service.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"></property>
</bean>
<!-- 配置持久层 -->
<bean id="customerDao" class="my.dao.CustomerDaoImpl">
</bean>
</beans>
log4j.properties
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c\:mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=info, stdout
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>day10</display-name>
<!-- 配置web整合的监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 加载方式:默认只能加载WEB-INF目录下的配置文件,提供配置方式,加载src目录 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
/**
* 日志的用法
* @author Administrator
*
*/
public class Demo1 {
private Logger log = Logger.getLogger(Demo1.class);
@Test
public void run1() {
System.out.println("执行");
log.info("执行了..");
}
}
/**
* 原来的方式
*/
@Test
public void run1() {
//创建实现类
UserServiceImpl usi = new UserServiceImpl();
usi.setName("小弟");
// UserService us = new UserServiceImpl();
usi.sayHello();
}
/**
* 使用spring框架的方式
*/
@Test
public void run2() {
//创建工厂,加载核心配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从工厂当中获取到对象
UserServiceImpl usi = (UserServiceImpl) ac.getBean("userService");
//调用对象的方法执行
usi.sayHello();
}
/**
* 接口的方式
*/
@Test
public void run3() {
//创建工厂,加载核心配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从工厂当中获取到对象
UserService us = (UserService) ac.getBean("userService");
//调用对象的方法执行
us.sayHello();
}
/**
* 老工厂版本 BeanFactory
*/
@Test
public void run4() {
BeanFactory factory = new XmlBeanFactory(new ClassPathResource("applicationContext.xml"));
UserService us = (UserService) factory.getBean("userService");
us.sayHello();
}
/**
* 销毁的方法
*/
@Test
public void run5() {
//创建工厂,加载核心配置文件
ClassPathXmlApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从工厂当中获取到对象
UserServiceImpl usi = (UserServiceImpl) ac.getBean("userService");
//调用对象的方法执行
usi.sayHello();
//关闭工厂,工厂关闭了,对象会销毁
ac.close();
}
/**
* 依赖注入感念
*/
@Test
public void run6() {
//创建工厂,加载核心配置文件
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
//从工厂当中获取到对象
UserService us = (UserService) ac.getBean("userService");
//调用对象的方法执行
us.sayHello();
}
}
/**
* 原始的方式
*/
@Test
public void run1() {
CustomerServiceImpl cs = new CustomerServiceImpl();
cs.save();
}
/**
* spring的方式
*/
@Test
public void run2() {
//创建工厂,加载配置文件,CustomerDaoImpl创建了,CustomerServiceImpl被创建了,
ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
CustomerServiceImpl cs = (CustomerServiceImpl) ac.getBean("customerService");
cs.save();
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<!-- 使用bean标签 -->
<bean id="userService" class="my.demo2.UserServiceImpl" >
<property name="name" value="小弟"></property>
</bean>
<!-- 依赖注入 -->
<bean id="customerDao" class="my.demo3.CustomerDaoImpl"></bean>
<bean id="customerService" class="my.demo3.CustomerServiceImpl">
<property name="customerDao" ref="customerDao"></property>
</bean>
<!-- 构造方法注入的方式 -->
<bean id="car1" class="my.demo4.Car1">
<!-- <constructor-arg name="cname" value="板车"></constructor-arg>
<constructor-arg name="price" value="2"></constructor-arg> -->
<constructor-arg index="0" value="大奔"></constructor-arg>
<constructor-arg index="1" value="33"></constructor-arg>
</bean>
<bean id="person" class="my.demo4.Person">
<constructor-arg name="pname" value="小弟"></constructor-arg>
<constructor-arg name="car1" ref="car1"></constructor-arg>
</bean>
<!-- 采用set方法注入 -->
<!-- <bean id="car2" class="my.demo4.Car2">
<property name="cname" value="幻影"></property>
<property name="price" value="3.23"></property>
</bean> -->
<!-- 采用p名称空间注入的方式 -->
<!-- <bean id="car2" class="my.demo4.Car2" p:cname="凯迪拉克" p:price="10000"/> -->
<!-- 使用SpEL方式注入 -->
<bean id="car2" class="my.demo4.Car2">
<property name="cname" value="#{'福特'}"></property>
<property name="price" value="#{31231.1}"></property>
</bean>
<!-- 注入集合
<bean id="user" class="my.demo4.User">
<property name="arrs" >
<list>
<value>小弟</value>
<value>小弟1</value>
<value>小弟2</value>
</list>
</property>
<property name="list" >
<list>
<value>大哥</value>
<value>大哥1</value>
<value>大哥2</value>
</list>
</property>
<property name="map" >
<map>
<entry key="aaa" value="啦啦啦"></entry>
<entry key="bbb" value="Wllala"></entry>
</map>
</property>
<property name="pro">
<props>
<prop key="username">root</prop>
<prop key="password">123</prop>
</props>
</property>
</bean>
-->
<!-- 引入其他的配置文件 my/xxx/applicationContext2.xml-->
<!-- <import resource="applicationContext2.xml"/> -->
</beans>
Action
public String save() {
System.out.println("web:保存客户");
//使用工厂
// ApplicationContext ac = new ClassPathXmlApplicationContext("applicationContext.xml");
// CustomerService cs = (CustomerService) ac.getBean("customerService");
// cs.save();
ServletContext servletContext = ServletActionContext.getServletContext();
//使用web工厂的方式
WebApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
CustomerService cs = (CustomerService) context.getBean("customerService");
cs.save();
return NONE;
}
}