Spring学习之路

Spring4

简介:Spring 作者:Rod Johnson;
官方网站:http://spring.io/
最新开发包及文档下载地址:http://repo.springsource.org/libs-release- local/org/springframework/spring/
核心思想:IOC 控制反转;AOP 面向切面;
介绍:百度百科;


核心jar包与配置文件
<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">

<bean id="helloWorld" class="com.java1234.test.HelloWorld"></bean>

</beans>




spring ioc 简介:
IOC(控制反转:Inverse of Control ),又称作 依赖注入,是一种重要的面向对象编程的法则来削减计算机程序 的耦合问题,也是轻量级的 Spring 框架的核心。

实例:比如研发经理需要找几名测试人员来进行测试不同的功能模块,首先需要定义一个Javawork类 里面定义一个doTest()方法。再需要定义一个员工ZhangSan类,里面定义一个test()方法,定义一个LiSi类里面定义一个test()方法,这样每多加一个人Javawork里面就要进行一次改动,很麻烦。因此可以通过定义接口的方式来解决此问题。定义一个tester接口,接口里面定义一个test方法。ZhangSan,LiSi都实现tester接口并重写其方法。在Javawork中定义一个tester对象,生成其set方法。然后在doTest方法中加入接口对象的test()方法就行。可通过在配置文件中设置人员进行测试工作。避免重复修改业务代码。具体方式如下:

<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">

<bean id="zhangsan" class="com.java1234.service.ZhangSan"></bean>
<bean id="lisi" class="com.java1234.service.Lisi"></bean>
<bean id="javaWork" class="com.java1234.service.JavaWork">
<property name=" tester" ref=" lisi"></property>
</bean>
</beans>

bean文件配置:依赖注入
1,属性注入;
<bean id="people2" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
</bean>
2,构造函数注入;(通过类型;通过索引;联合使用)
<bean id="people3" class="com.java1234.entity.People"> //通过类型;
<constructor-arg type="int" value="2"></constructor-arg>
<constructor-arg type="String" value="李四"></constructor-arg>
<constructor-arg type="int" value="22"></constructor-arg>
</bean>
<bean id="people4" class="com.java1234.entity.People"> //通过索引;
<constructor-arg index="0" value="3"></constructor-arg>
<constructor-arg index="1" value="王五"></constructor-arg>
<constructor-arg index="2" value="55"></constructor-arg>
</bean>
<bean id="people5" class="com.java1234.entity.People"> //联合使用
<constructor-arg index="0" type="int" value="4"></constructor-arg>
<constructor-arg index="1" type="String" value="招六"></constructor-arg>
<constructor-arg index="2" type="int" value="66"></constructor-arg>
</bean>
3,工厂方法注入;(非静态工厂,静态工厂)
//非静态工厂
<bean id=" peopleFactory" class="com.java1234.factory. PeopleFactory"></bean>
<bean id="people7" factory-bean=" peopleFactory" factory-method="createPeople"(工厂类中的方法)></bean>
//静态工厂
<bean id="people8" class="com.java1234.factory.PeopleFactory2" factory-method="createPeople"></bean>
4,泛型依赖注入;(后面补上)

注入参数:

1,基本类型值;
和前面一样
2,注入 bean;
<bean id="dog1" class="com.java1234.entity.Dog">
<property name="name" value="jack"></property>
</bean>

<bean id="people2" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="ser"></property>
<property name="age" value="13"></property>
<property name="dog" ref="dog1"></property>
</bean>
3,内部 bean;
<bean id="people3" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
<property name="dog">
<bean class="com.java1234.entity.Dog">
<property name="name" value="Tom"></property>
</bean>
</property>
</bean>
4,null 值;
<bean id="people4" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
<property name="dog">
<null></null>
</property>
</bean>
5,级联属性;
<bean id="people5" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
<property name="dog.name" value="Jack2"></property>
</bean>
6,集合类型属性;
<bean id="people6" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
<property name="dog" ref="dog1"></property>
<property name="hobbies">
<list>
<value>唱歌</value>
<value>跳舞</value>
</list>
</property>
<property name="loves">
<set>
<value>唱歌2</value>
<value>跳舞2</value>
</set>
</property>
<property name="works">
<map>
<entry>
<key><value>上午</value></key>
<value>写代码</value>
</entry>
<entry>
<key><value>下午</value></key>
<value>测试代码</value>
</entry>
</map>
</property>
<property name="addresses">
<props>
<prop key="address1">aaaaa</prop>
<prop key="address2">bbbbb</prop>
</props>
</property>
</bean>

Spring 自动装配
通过配置 default-autowire 属性,Spring IOC 容器可以自动为程序注入 bean;默认是 no,不启用自动装配; default-autowire 的类型有 byName,byType,constructor; byName:通过名称进行自动匹配; byType:根据类型进行自动匹配; constructor:和 byType 类似,只不过它是根据构造方法注入而言的,根据类型,自动注入;

实现细节:<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"
default-autowire=" constructor ">
建议:自动装配机制慎用,它屏蔽了装配细节,容易产生潜在的错误;

方法注入
Spring bean 作用域默认是 单例 singleton; 可以通过配置 prototype ,实现多例; 方法注入 lookup-method

方法替换
在Dog类中设置狗的名字为jack,在People类中设置狗的名字为Tom。然后people类实现methodreplacer接口,重写其方法,把设置狗名字的方法添加进去。
配置实现细节:
<bean id="people1" class="com.java1234.entity.People">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
<property name="age" value="11"></property>
<replaced-method name="getDog" replacer="people2"></replaced-method>
</bean>
<bean id="people2" class="com.java1234.entity.People2"></bean>

bean 之间的关系

1,继承;
<bean id="abstractPeople" class="com.java1234.entity.People" abstract="true">
<property name="className" value="高三5班"></property>
<property name="age" value="19"></property>
</bean>
<bean id="zhangsan" parent="abstractPeople" >
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
</bean>
<bean id="lisi" parent="abstractPeople">
<property name="id" value="2"></property>
<property name="name" value="李四"></property>
<property name="age" value="20"></property>
<property name="dog" ref="dog"></property>
</bean>
2,依赖;
<bean id="abstractPeople" class="com.java1234.entity.People" abstract="true">
<property name="className" value="高三5班"></property>
<property name="age" value="19"></property>
</bean>
<bean id="autority" class="com.java1234.service.Authority"(权限验证类)></bean>
</beans>
<bean id="zhangsan" parent="abstractPeople" depends-on="autority">
<property name="id" value="1"></property>
<property name="name" value="张三"></property>
</bean>
<bean id="lisi" parent="abstractPeople">
<property name="id" value="2"></property>
<property name="name" value="李四"></property>
<property name="age" value="20"></property>
<property name="dog" ref="dog"></property>

3,引用;

bean 作用范围

1,singleton Spring ioc 容器中仅有一个 Bean 实例,Bean 以单例的方式存在;
2,prototype 每次从容器中调用 Bean 时,都返回一个新的实例;
3,request 每次 HTTP 请求都会创建一个新的 Bean;
4,session 同一个 HTTP Session 共享一个 Bean;
5,global session 同一个全局 Session 共享一个 Bean,一般用于 Portlet 应用环境;
6,application 同一个 Application 共享一个 Bean;

AOP 简介

AOP 简介:百度百科; 面向切面编程(也叫面向方面编程):Aspect Oriented Programming(AOP),是软件开发中的一个热点,也是 Spring 框架中的一个重要内容。利用 AOP 可以对业务逻辑的各个部分进行隔离,从而使得业务逻辑各部分之间的耦合度 降低,提高程序的可重用性,同时提高了开发的效率。 主要的功能是:日志记录,性能统计,安全控制,事务处理,异常处理等等。

Spring AOP 实例

<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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop/spring-aop.xsd">
<bean id="studentServiceAspect" class="com.java1234.advice.StudentServiceAspect"></bean>
<bean id="studentService" class="com.java1234.service.impl.StudentService"></bean>
<aop:config>
<aop:aspect id="studentServiceAspect" ref="studentServiceAspect">
<aop:pointcut expression="execution(* com.java1234.service.*.*(..))" id="businessService"/>
<aop:before method="doBefore" pointcut-ref="businessService"/> 1,前置通知;
<aop:after method="doAfter" pointcut-ref="businessService"/> 2,后置通知;
<aop:around method="doAround" pointcut-ref="businessService"/> 3,环绕通知;
<aop:after-returning method="doAfterReturning" pointcut-ref="businessService"/> 4,返回通知;
<aop:after-throwing method="doAfterThrowing" pointcut-ref="businessService" throwing="ex"/> 5,异常通知;
</aop:aspect>
</aop:config>
</beans>

Spring 对 DAO 的支持

Spring对jdbc的支持
1,配置数据源 dbcp;

2,使用 JdbcTemplate;

<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"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<context:property-placeholder location="jdbc.properties"/>
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="studentDao" class="com.java1234.dao.impl.StudentDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplate"></property>
</bean>
<bean id="studentService" class="com.java1234.service.impl.StudentServiceImpl">
<property name="studentDao" ref="studentDao"></property>
</bean>
</beans>
实例:

3,JdbcDaoSupport 的使用;
public class StudentDaoImpl extends JdbcDaoSupport implements StudentDao{

@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null,?,?)";
Object []params=new Object[]{student.getName(),student.getAge()};
return this.getJdbcTemplate().update(sql,params);
}
}

配置文件中不需要再配置 jdbcTemplate。实际上和上面实例的jdbcTemplate对比就是简化了代码量,源码里面已经定义了。
4,NamedParameterJdbcTemplate 的使用;支持命名参数变量; org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate
和上面实例对比 jdbcTemplate 的引用类变化了
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
dao层定义SQL时,具体的参数可以明显的体现出来 格式( :参数名),然后通过 MapSqlParameterSource 对参数名进行定义
@Override
public int addStudent(Student student) {
String sql="insert into t_student values(null, :name , :age)";
MapSqlParameterSource sps=new MapSqlParameterSource();
sps.addValue("name", student.getName());
sps.addValue("age", student.getAge());
return namedParameterJdbcTemplate.update(sql,sps);
}


事务简介:
满足一下四个条件:
第一:原子性;
第二:一致性;
第三:隔离性;
第四:持久性;

编程式事务管理
Spring 提供的事务模版类:org.springframework.transaction.support.TransactionTemplate 事务管理器:org.springframework.jdbc.datasource.DataSourceTransactionManager
缺点:非业务代码侵入业务逻辑代码,掺杂在一起。不利于维护

实例:A转账给B,正常的业务逻辑是A(count)-count,B(count)+count。但是有时程序会出现异常,导致A钱转出来了,B没有收到。造成业务损失,可用编程式事务管理,当程序代码运行出现异常时,进行事务回滚,恢复到原来的状态。

配置:
<?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
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- jdbc事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
<property name="transactionManager" ref="transactionManager"></property>
</bean>
<context:property-placeholder location="jdbc.properties"/>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="bankDao" class="com.java1234.dao.imp.BankDaoImp">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean>
<bean id="bankService" class="com.java1234.service.BankService">
<property name="bankDao" ref="bankDao"></property>
<property name="transactionTemplate" ref="transactionTemplate"></property>
</bean>
</beans>

实例代码:


声明式事务管理
推荐使用xml配置方式,配置方便。注解方式在少量service的小型项目中可使用,但是大型项目就不太方便了。
1,使用 XML 配置声明式事务;
将service中的编程式事务管理代码去掉,配置实例:<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"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- jdbc事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置事务切面 -->
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(*(表示方法返回值) com.java1234.service.*(类).*(方法)(..(属性)))" id="serviceMethod"></aop:pointcut>
<!-- 配置事务通知 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>
<context:property-placeholder location="jdbc.properties"/>
<bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource"></constructor-arg>
</bean>
<bean id="bankDao" class="com.java1234.dao.imp.BankDaoImp">
<property name="namedParameterJdbcTemplate" ref="namedParameterJdbcTemplate"></property>
</bean>
<bean id="bankService" class="com.java1234.service.BankService">
<property name="bankDao" ref="bankDao"></property>
</bean>
</beans>
2,使用注解配置声明式事务;
在service类中添加注解@Transactional 配置文件中的切面配置就不需要了
<!--配置事务通知-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"></tx:method>
</tx:attributes>
</tx:advice>
<!-- 配置事务切面 -->
<aop:config>
<!-- 配置切点 -->
<aop:pointcut expression="execution(* com.java1234.service.*.*(..))" id="serviceMethod"></aop:pointcut>
<!-- 配置事务通知 -->
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethod"/>
</aop:config>

但是需要添加一个配置:
<tx:annotation-driven transaction-manager="transactionManager"/>


事务传播行为

事务传播行为:Spring 中,当一个 service 方法调用另外一个 service 方法的时候,因为每个 service 方法都有事 务,这时候就出现了事务的嵌套;由此,就产生了事务传播行为; 在 Spring 中,通过配置 Propagation,来定义事务传播行为;
PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。 PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。 PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。 PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常。

<tx:attributes> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="edit*" propagation="REQUIRED" /> <tx:method name="save*" propagation="REQUIRED" /> <tx:method name="add*" propagation="REQUIRED" /> <tx:method name="new*" propagation="REQUIRED" /> <tx:method name="set*" propagation="REQUIRED" /> <tx:method name="remove*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="change*" propagation="REQUIRED" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="find*" propagation="REQUIRED" read-only="true" /> <tx:method name="load*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="true" /> </tx:attributes>


Spring4 整合 Hibernate4,Struts2

S2SH 整合所需 Jar 包


Spring4 接管 Hibernate4 所有 Bean 实例,以及 SessionFactory,事务管理器;
Spring4 接管 Struts2 所有 Bean 实例;

web.xml配置
<!-- 添加对spring的支持 -->
<context-param>
<param-name> contextConfigLocation</param-name>
<param-value>classpath: applicationContext.xml</param-value>
</context-param>
<!-- 定义Spring监听器,加载Spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 添加对struts2的支持 -->
<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>
<!-- Session延迟加载到页面 -->
<filter>
<filter-name>openSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.hibernate4.support.OpenSessionInViewFilter</filter-class>
<init-param>
<param-name>singleSession</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>openSessionInViewFilter</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>

三个框架的配置文件:


S2SH实例:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值