Spring
负责整个应用
是业务逻辑组件框架
目的:程序结构良好,简化开发
必须要会 很重要
Spring开发包
dist/
spring.jar spring核心jar包
spring-src.zip
modules/目录下将 spring核心jar包 拆分若干个子包
resources/目录 包括了spring的配置文件(.dtd .xsd .ftl .tld)
docs/
api和reference【官方文档】
lib/
spring开发时所依赖的第三方jar包
Spring主要内容
IOC 容器 :使组件关系松散
AOP 容器 :使我们的应用易于扩展
通用支持 :简化开发
三层:持久 业务 表示
----
IOC 容器
概念:
IOC: Inversion Of Control【反转控制】
例如:对象由容器控制,拿就从容器中拿使用
DI:Dependency Injection【依赖注入】
IOC容器的类型:
BeanFactory 核心组件
延迟实例化组件【用的时候才创建】
ApplicationContext 扩展了BeanFactory
配置实例化时机,默认预先实例化
实现类:加载资源的相对路径不同
ClassPathXmlApplicationContext
FileSystemXmlApplicationContext
配置
装备/注入
装配的属性的类型
简单值:8种基本类型,String Class Resource
使用属性value
其它Bean引用类型: 使用属性ref
集合类型:List Set Map Properties 数组
实例化了组件
初始化/销毁
<bean init-method="" destroy-method="">
Bean的生命周期
实例化->DI->初始化方法->就绪状态
->使用->销毁方法->从容器中删除Bean【对象还在内存】
实例化途径
无参构造方法【默认】
<bean class=""></bean>
有参构造方法
<bean>
<constructor-arg index="" type="">
</constructor-arg>
</bean>
静态工厂
<bean factory-method="">
</bean>
实例工厂
<bean factory-bean=""
factory-method="">
</bean>
实例化时机
ApplicationContext 默认,预先实例化<bean lazy-init="">
BeanFactory 只能延迟实例化 配置对它无效
组件的作用域
默认组件是单例的
<bean scope=""></bean>
取值:singleton:单例 prototype:每次获得新对象
继承配置
<bean parent=""> 继承莫个bean
多个不同的Bean需要相同的配置
同一个类型的Bean多个实例需要相同的配置
容器不会创建当前的bean <bean abstract="true"></bean>
Resource
表示文件
Resource resource = new ClassPathResource("ioc11/a.txt");
Resource resource2 = ac.getResource("classpath:ioc11/a.txt");
获得当前Bean所在容器
实现ApplicationContextAware
自动装配
<bean autowire="">
取值:byType【根据属性类型匹配】
byName 【根据属性的名字匹配】
constructor 【根据构造方法参数类型匹配】
autodetect 【自动,先byType再constructor】
FactoryBean
用于复杂的对象创建过程
创建的Bean要实现 Factorybean接口 默认会执行getObject方法
创建的对象不是自己
后处理Bean
实例化->DI->postProcessBeforeInitialization->初始化方法->postProcessAfterInitialization->就绪状态
->使用->销毁方法->从容器中删除Bean
后处理Bean会对当前容器中的所有Bean做后处理
常用于:修改Bean 替换成代理 annotation[标注]
属性编辑
1、要编写属性转化规则 extends PropertyEditorSupport
2、用后处理 去添加这些规则
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
CustomEditorConfigurer继承的是 BeanFactoryPostProcessor 对容器做后处理
Spring提供的属性编辑器
org.springframework.beans.propertyeditors包下
访问properties文件
================================================================
相关代码:
applicationContext.xml
<bean id="userDao" class="dao.impl.UserDaoImpl"></bean>
<bean id="userService" class="service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
Test:
Resource resource = new ClassPathResource("applicationContext.xml");
BeanFactory beanFactory = new XmlBeanFactory(resource);
//ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext.xml");
//ApplicationContext ac =
new ClassPathXmlApplicationContext(new String[]{"xx/xxx.xml","yy/yyy.xml"});
ApplicationContext ac =
new ClassPathXmlApplicationContext("applicationContext*.xml");
IUserService userService = (IUserService)beanFactory.getBean("userService");
userService.regist();
-------
<!-- 简单类型装配 -->
<!-- <bean id="someBean" class="ioc1.SomeBean">-->
<!-- <property name="str">-->
<!-- <value>abc</value>-->
<!-- </property>-->
<!-- <property name="var">-->
<!-- <value>123</value>-->
<!-- </property>-->
<!-- <property name="c">-->
<!-- <value>ioc1.SomeBean</value>-->
<!-- </property>-->
<!-- </bean>-->
<bean id="someBean" class="ioc1.SomeBean">
<property name="str" value="abc"></property>
<property name="var" value="1234"></property>
<property name="c" value="java.lang.String"></property>
</bean>
--------
其它Bean引用类型:
一个Bean中 包含其它Bean
<!-- <bean id="someBean" class="ioc2.SomeBean">-->
<!-- <property name="otherBean" ref="otherBean"></property>-->
<!-- </bean>-->
<bean id="someBean" class="ioc2.SomeBean">
<property name="otherBean">
<ref bean="otherBean"/>
</property>
</bean>
---
集合类型
<bean id="someBean" class="ioc3.SomeBean">
<property name="list">
<list>
<value>aaa</value>
<value>bbb</value>
<value>ccc</value>
</list>
</property>
<property name="set">
<set>
<value>ddd</value>
<value>eee</value>
</set>
</property>
<property name="map">
<map>
<entry key="a" value="123"></entry>
<entry key="b" value="456"></entry>
</map>
</property>
<property name="props">
<props>
<prop key="aaa">111</prop>
<prop key="bbb">222</prop>
</props>
</property>
<property name="arrays">
<list>
<value>a</value>
<value>b</value>
</list>
</property>
</bean>
实例化组件:
<bean id="someBean" class="ioc4.SomeBean" init-method="init" destroy-method="destroy">
<property name="str" value="abc"></property>
</bean>
//主动销毁
//ac.destroy();
//关闭虚拟时销毁容器中的Bean
ac.registerShutdownHook();
----------
有参构造方法:
<bean id="someBean" class="ioc5.SomeBean">
<constructor-arg index="0" type="java.lang.String">
<value>111</value>
</constructor-arg>
<constructor-arg index="2" type="int">
<value>222</value>
</constructor-arg>
<constructor-arg index="1" type="java.lang.String">
<value>333</value>
</constructor-arg>
</bean>
-----
静态工厂:
无参的
<bean id="someBean" class="ioc6.SomeBeanFactory" factory-method="getSomeBean"></bean>
有参的
<bean id="path" class="java.lang.System" factory-method="getenv">
<constructor-arg>
<value>PATH</value>
</constructor-arg>
</bean>
------
实例工厂:
<bean id="someBeanFactory" class="ioc7.SomeBeanFactory"></bean>
<bean id="someBean" factory-bean="someBeanFactory" factory-method="getSomeBean"></bean>
-----
继承配置
1、多个不同的Bean需要相同的配置
<bean id="abstractBean" abstract="true">
<property name="some" value="some"></property>
</bean>
<bean id="someBean" class="ioc10.SomeBean" parent="abstractBean"></bean>
<bean id="otherBean" class="ioc10.OtherBean" parent="abstractBean"></bean>
2、同一个类型的Bean多个实例需要相同的配置
<bean id="abstractSomeBean" class="ioc10.SomeBean">
<property name="some" value="some"></property>
</bean>
<bean id="someBean1" parent="abstractSomeBean">
<property name="other" value="other1"></property>
</bean>
<bean id="someBean2" parent="abstractSomeBean">
<property name="other" value="other2"></property>
</bean>
-----
Resource:
<bean id="someBean" class="ioc11.SomeBean">
<property name="resource" value="classpath:ioc11/a.txt"></property>
</bean>
Test:
Resource resource = new ClassPathResource("ioc11/a.txt");
System.out.println(resource.getFile().length());
ApplicationContext ac = new ClassPathXmlApplicationContext("ioc11/applicationContext.xml");
Resource resource2 = ac.getResource("classpath:ioc11/a.txt");
System.out.println(resource2.getFile().length());
System.out.println(ac);
SomeBean someBean = (SomeBean)ac.getBean("someBean");
Resource resource3 = someBean.getResource();
System.out.println(resource3.getFile().length());
someBean.doSome();
自动装配:
------
<bean id="otherBean" class="ioc12.OtherBean">
<property name="str" value="abc"></property>
</bean>
<bean id="someBean" class="ioc12.SomeBean" autowire="byType"></bean>
FactoryBean
----------
public class SAXParserFactoryBean implements FactoryBean
{
getObject();
getObjectType();
isSingleton();
}
applicationContext.xml配置
<bean id="parser" class="ioc13.SAXParserFactoryBean"></bean>
后处理:
------
public class SomeBeanPropertyPostProcess implements BeanPostProcessor
<bean id="someBean" class="ioc14.SomeBean">
<property name="str" value="aSCll"></property>
</bean>
<bean class="ioc14.SomeBeanPropertyPostProcess"></bean>
属性编辑
------
<bean id="person" class="ioc15.Person">
<property name="addr" value="江苏省-南京市" />
<property name="birthday" value="1955/11/11" />
<property name="hobbies" value="吃,玩,睡"/>
</bean>
<bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="ioc15.Address">
<bean class="ioc15.AddressEditor"></bean>
</entry>
<entry key="java.util.Date">
<bean class="ioc15.DateEditor">
<property name="format" value="yyyy/MM/dd"></property>
</bean>
<bean class="org.springframework.beans.propertyeditors.CustomDateEditor">
<constructor-arg>
<bean class="java.text.SimpleDateFormat">
<constructor-arg>
<value>yyyy/MM/dd</value>
</constructor-arg>
</bean>
</constructor-arg>
<constructor-arg>
<value>true</value>
</constructor-arg>
</bean>
</entry>
</map>
</property>
</bean>
public class AddressEditor extends PropertyEditorSupport
{
@Override
public void setAsText(String text)
throws IllegalArgumentException
{
String[] ss = text.split(" ");
Address address = new Address();
address.setProvince(ss[0]);
address.setCity(ss[1]);
setValue(address);
}
}
访问properties文件
--------
<bean id="someBean" class="ioc16.SomeBean">
<property name="str" value="${str}"></property>
<property name="var" value="${var}"></property>
</bean>
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location">
<value>classpath:ioc16/info.properties</value>
</property>
</bean>
---------------------------------------------------------------------------
AOP容器
Aspect Oriented Programming【面向切面编程】
将应用中的交叉业务逻辑(事务,安全,日志,缓存,等)
提取出来,封装成切面
由AOP容器在适当的时机(编译或运行)
将这些切面动态织入到具体的业务逻辑中
将程序中交叉业务逻辑抽象成切面
实现切面的复用
并且解藕了交叉业务逻辑代码和具体业务逻辑代码
应用的关注点
业务逻辑,安全,事务,日志,缓存等
横切关注点:业务逻辑之外的其它关注点
AOP目的:把横切关注点从业务逻辑中分离
独立模块化
在不改变现有代码基础上动态添加功能
名词:
AOP原理:采用动态代理模式
静态代理:是实现同样的接口 调用原有的实现类的方法
动态代理:依据目标类,代理接口,交叉业务逻辑代码
自动生成代理
java.lang.reflect.Proxy.newProcyInstance
(ClassLoader loader, 目标类的类加载器
Class<?>[] interfaces,代理接口
InvocationHandler h) 交叉业务逻辑代码
Spring AOP采用动态代理的过程
Spring在默认情况下(Bean类实现了代理接口),
使用动态代理模式实现AOP
Bean类没有实现接口
Spring使用CGLib类生成代理对象
该对象是目标对象的子类对象
因此Bean不能是final类
目标类如果是final类,并且没有实现代理接口,不能是用AOP
Spring 1.x FactoryBean
1、通知(Advice)
通知类型 接口
Around环绕通知 MethodInterceptor
Before前置通知 MethodBeforeAdvice
After后置通知 AfterReturningAdvice
Throws异常通知 ThrowsAdvice
2、ProxyFactoryBean
Advisor
Advisor=Advice+Pointcut
通知 切入点
//自定义切入点
public class MyPointcut implements Pointcut
public class LogAdvisor implements PointcutAdvisor
预定义切入点
org.springframework.aop.support包下
NameMatchMethodPointcutAdvisor
自动代理
多个目标对象使用相同的切面
Spring AOP 2.x 后处理
特点:非侵入性,完全基于xml配置,使用AspectJ的切点表达式
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:aop="http://www.springframework.org/schema/aop"
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-2.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
切点表达式:
within:匹配类的所有方法 within(包名.类名)
execution:匹配指定的方法
execution(void doSome())
execution(java.lang.String
doSome(java.lang.String))
execution(void aop8.SomeServiceImpl.doOther())
execution(* doSome())
execution(* doSome(..))参数,返回值不限定
execution(* doSome(*)) 必须有一个参数,参数任意
execution(* aop8.OtherServiceImpl.doSome(..,java.lang.String))
execution(* do*(..))
execution(* *(..))所有类的所有方法,会报堆栈溢出
execution(* aop8.SomeServiceImpl.*(..))=within(aop8.SomeServiceImpl)
execution(* aop8.*.*(..))
execution(* aop8.*ServiceImpl.*(..))
execution(* aop8..*.*(..))
not and or
SomeService doSome OtherService
execution(* aop8.SomeServiceImpl.doSome(..)) or within(aop8.OtherServiceImpl)
Advice
before
after:after-returning after-throwing
around 对方法有以下要求:
1.返回类型是Object
2.参数ProceedingJoinPoint
3.throws Throwable
====================================相关代码=================================
动态代理
public static void main(String[] args)
{
ISomeService someService = (ISomeService)Proxy.newProxyInstance
(SomeServiceImpl.class.getClassLoader(),
SomeServiceImpl.class.getInterfaces(),
new LogInvocationHandler(new SomeServiceImpl()));
someService.doSome();
someService.doOther();
}
public class LogInvocationHandler implements InvocationHandler
{
private Object target;
public LogInvocationHandler(Object target)
{
this.target = target;
}
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable
{
System.out.println(method.getName()+"execute at:"+new Date());
return method.invoke(target, args);
}
}
Spring 1.x
<bean id="someServiceTarget" class="aop3.SomeServiceImpl"></bean>
<bean id="logAdvice" class="aop3.LogAdvice"></bean>
<bean id="welcomeAdvice" class="aop3.WelcomeAdvice"></bean>
<bean id="timeInterceptor" class="aop3.TimeInterceptor"></bean>
<bean id="someService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="someServiceTarget"></property>
<property name="proxyInterfaces" value="aop3.ISomeService"></property>
<property name="interceptorNames">
<list>
<value>logAdvice</value>
<value>timeInterceptor</value>
<value>welcomeAdvice</value>
</list>
</property>
</bean>
//环绕通知
public class TimeInterceptor implements MethodInterceptor{
public Object invoke(MethodInvocation invocation) throws Throwable {
Method method=invocation.getMethod();
Object[] args=invocation.getArguments();
Object target=invocation.getThis();
System.out.println("开始");
long start=System.currentTimeMillis();
Object result=invocation.proceed();//执行下一个组件
long end=System.currentTimeMillis();
System.out.println("结束");
System.out.println(method.getName()+" "+(end-start));
return result;
}
}
//前置通知
public class LogAdvice implements MethodBeforeAdvice{
public void before(Method method, Object[] args, Object target) throws Throwable {
System.out.println(method.getName()+" execute at:"+new Date());
}
}
//后置通知
public class WelcomeAdvice implements AfterReturningAdvice{
public void afterReturning(Object returnValue, Method method, Object[] args, Object target) throws Throwable {
System.out.println("welcome");
}
}
异常通知
public class ServiceExceptionAdvice implements ThrowsAdvice
{
public void afterThrowing(Exception ex)
{
System.out.println("exception");
}
}
<!-- advisor -->
------------------------
<bean id="someServiceTarget" class="aop5.SomeServiceImpl"></bean>
<bean id="otherServiceTarget" class="aop5.OtherServiceImpl"></bean>
<bean id="logAdvice" class="aop5.LogAdvice"></bean>
<bean id="myPointcut" class="aop5.MyPointcut"></bean>
<bean id="logAdvisor" class="aop5.LogAdvisor">
<property name="advice" ref="logAdvice"></property>
<property name="pointcut" ref="myPointcut"></property>
</bean>
<bean id="someService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="someServiceTarget"></property>
<property name="proxyInterfaces" value="aop5.ISomeService"></property>
<property name="interceptorNames">
<value>logAdvisor</value>
</property>
</bean>
<bean id="otherService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="otherServiceTarget"></property>
<property name="proxyInterfaces" value="aop5.IOtherService"></property>
<property name="interceptorNames">
<value>logAdvisor</value>
</property>
</bean>
<!-- 预定义切入点 -->
----------------------
<bean id="someServiceTarget" class="aop6.SomeServiceImpl"></bean>
<bean id="logAdvice" class="aop6.LogAdvice"></bean>
<bean id="logAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice" ref="logAdvice"></property>
<property name="mappedNames">
<list>
<!-- <value>doSome</value>-->
<!-- <value>doOther</value>-->
<value>do*</value>
</list>
</property>
</bean>
<bean id="someService" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="target" ref="someServiceTarget"></property>
<property name="proxyInterfaces" value="aop6.ISomeService"></property>
<property name="interceptorNames">
<list>
<value>logAdvisor</value>
</list>
</property>
</bean>
自动代理
--------
<bean id="someService" class="aop7.SomeServiceImpl"></bean>
<bean id="otherService" class="aop7.OtherServiceImpl"></bean>
<bean id="logAdvice" class="aop7.LogAdvice"></bean>
<bean id="logAdvisor" class="org.springframework.aop.support.NameMatchMethodPointcutAdvisor">
<property name="advice" ref="logAdvice"></property>
<property name="mappedNames">
<list>
<value>doOther</value>
</list>
</property>
</bean>
<bean class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>*Service</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>logAdvisor</value>
</list>
</property>
</bean>
Spring AOP 2.x
<bean id="someService" class="aop8.SomeServiceImpl"></bean>
<bean id="otherService" class="aop8.OtherServiceImpl"></bean>
<bean id="logAdvice" class="aop8.LogAdvice"></bean>
<aop:config>
<aop:pointcut id="pc1" expression="within(aop8.SomeServiceImpl)"/>
<aop:pointcut id="pc2" expression="within(aop8.OtherServiceImpl)"/>
<aop:aspect ref="logAdvice">
<aop:before pointcut-ref="pc1" method="log"/>
<aop:after pointcut-ref="pc2" method="log"/>
</aop:aspect>
</aop:config>
环绕通知java类
public Object time(ProceedingJoinPoint point) throws Throwable
{
String methodName = point.getSignature().getName();
Object[] args = point.getArgs();
Object target = point.getThis();
System.out.println("开始");
long start = System.currentTimeMillis();
Object result = point.proceed();
long end = System.currentTimeMillis();
System.out.println("结束");
System.out.println(methodName+" "+(end-start));
return result;
}
一个类获取参数信息
public class Log
{
public void before(JoinPoint jp)
{
int size = jp.getArgs().length;
String methodName = jp.getSignature().getName();
System.out.println("----------方法"+methodName+"即将执行,参数个数="+size);
}
public void afterReturning(JoinPoint jp,Object result)
{
String methodName = jp.getSignature().getName();
System.out.println("----------方法"+methodName+"已经返回,返回值="+result);
}
public void afterThrowing(JoinPoint jp,Exception e)
{
String methodName = jp.getSignature().getName();
System.out.println("----------方法"+methodName+"已出错,异常="+e);
}
}
<aop:aspect ref="log">
<aop:before pointcut-ref="pc2" method="before"/>
<aop:after-returning pointcut-ref="pc2" method="afterReturning" returning="result"/>
<aop:after-throwing pointcut-ref="pc2" method="afterThrowing" throwing="e"/>
</aop:aspect>
execution切点表达式
<aop:pointcut id="pc1" expression="within(aop8.SomeServiceImpl)"/>
<aop:pointcut id="pc2" expression="within(aop8.OtherServiceImpl)"/>
<aop:pointcut id="pc" expression="execution(void aop8.SomeServiceImpl.doSome(..)) or execution(* aop8.OtherServiceImpl.*(..))"/>
====================================================================
支持
Spring对数据访问的支持Dao,采用模板模式
模板类:
包装了持久化技术的操作,简化编程的重复代码
提供与平台无关的异常转换
RuntimeException
DateIntegrityViolationException 违反了约束
DateAccessResourceFailureException数据访问资源失败
InvalidDateAccessResourceUsageException使用错误的sql语句
回调接口:暴露底层api
数据源配置:
方式一:Spring内置的数据源 DriverManagerDateSource
方式二:使用第三方DataSource
org.apache.commons.dbcp.BasicDataSource
方式三:JNDI数据源
JDBC支持
1、使用JdbcTemplate
配置
dataSource-》jdbcTemplate->Dao
使用 Dao注入JdbcTemplate
方法:execute query queryXxx update
2、使用JdbcDaoSupport
配置
dataSource->Dao
使用 Dao继承JdbcDaoSupport
使用getJdbcTemplate()获得模板
Hibernate支持
1、使用HibernateTemplate
配置:
dataSource->sessionFactory->hibernateTemplate->Dao
使用:
Dao注入HibernateTemplate
2、使用HibernateDaoSupport
配置:
dataSource->sessionFactory->Dao
使用:
Dao继承HibernateDaoSupport
使用getHibernateTemplate()
3、本地Hibernate
配置:
dataSource->sessionFactory->Dao
配置一个后处理Bean
使用:
Dao注入SessionFactory
使用sessionFactory.getCurrentSession()获得Session
spring开发包
lib/
dom4j/dom4j.jar
j2ee/jta.jar
jakarta-commons/commons-pool.jar
commons-collections.jar
antlr/antrl-2.7.6.jar
事务支持【三种方法】
事务管理器TransactionManager
jdbc
org.springframwork.jdbc.datasource.DataSourceTransactionManager
dataSource->transactionManager
hibernate
org.springframework.orm.hibernate.HibernateTransactionManager
sessionFactory->transactionManager
事务属性:
传播属性:propagation
用的多的就是以下两种
REQUIRED
当前没有事务---》新建事务
当前有事务 ---》加入事务
SUPPORTS【查询】
没有事务 ---》 没事务
有事务 ---》加入事务
回滚条件:
默认:RuntimeException以及子类 回滚
rollback-for="异常类型" -异常类型
no-rollback-for="" +
只读优化:
readOnly read-only=""
隔离级别:
isolation
超时处理:
timeout=""
web支持
实例化ac
使用Listener实例化ac,并将ac放入ServletContext空间
从ac获取Bean
========================================================================
方式一:Spring内置的数据源 DriverManagerDateSource
------------------------------
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=utf8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123</value>
</property>
</bean>
方式二:使用第三方DataSource
-----------------------
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<property name="url">
<value>jdbc:mysql://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=utf8</value>
</property>
<property name="username">
<value>root</value>
</property>
<property name="password">
<value>123</value>
</property>
<property name="initialSize">
<value>1</value>
</property>
<property name="maxActive">
<value>1</value>
</property>
<property name="maxWait">
<value>5000</value>
</property>
</bean>
方式三:JNDI数据源
----------------
<bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName">
<value>xxxx</value>
</property>
</bean>
使用JdbcTemplate
----------------
<bean id="jt" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="userDaoImpl2" class="dao.impl.UserDaoImpl2">
<property name="jt" ref="jt"></property>
</bean>
使用JdbcDaoSupport
-----------------
<bean id="userDaoImpl" class="dao.impl.UserDaoImpl">
<property name="dataSource" ref="dataSource"></property>
</bean>
Spring-Hibernate支持【自动生成配置文件】
-------------------------
<bean id="dataSource"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver">
</property>
<property name="url"
value="jdbc:mysql://127.0.0.1:3306/spring?useUnicode=true&characterEncoding=utf8">
</property>
<property name="username" value="root"></property>
<property name="password" value=""></property>
</bean>
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<!-- <property name="configLocation" value="hibernate.cfg.xml"></property>-->
<property name="dataSource">
<ref bean="dataSource" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">
org.hibernate.dialect.MySQLDialect
</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
<property name="mappingResources">
<list>
<value>entity/User.hbm.xml</value></list>
</property></bean>
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!--使用HibernateTemplate -->
<bean id="userDaoImpl" class="dao.impl.UserDaoImpl">
<property name="hibernateTemplate" ref="hibernateTemplate"></property>
</bean>
<!--使用HibernateDaoSupport -->
<bean id="userDaoImpl2" class="dao.impl.UserDaoImpl2">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
事务支持 1.x 方法一
-------
<bean id="userDao" class="dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userServiceTarget" class="service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean">
<property name="target" ref="userServiceTarget"></property>
<property name="proxyInterfaces" value="service.UserService"></property>
<property name="transactionManager" ref="transactionManager"></property>
<property name="transactionAttributes">
<props>
<prop key="add">PROPAGATION_REQUIRED,-java.lang.Exception</prop>
<prop key="find*">PROPAGATION_SUPPORTS,readOnly</prop>
<prop key="*">PROPAGATION_REQUIRED</prop>
</props>
</property>
</bean>
事务支持 2.x 方法二
------------
<bean id="userDao" class="dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" read-only="true" rollback-for="java.lang.Exception"/>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="service"
expression="execution(* service.impl.*ServiceImpl.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="service"/>
</aop:config>
事务支持 方法三
--------------
<bean id="userDao" class="dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean id="userService" class="service.impl.UserServiceImpl">
<property name="userDao" ref="userDao"></property>
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
业务类中使用【方法和类都可以加 标注】
//@Transactional(propagation=Propagation.REQUIRED,rollbackFor={Exception.class,IOException.class})
@Transactional(propagation=Propagation.REQUIRED,rollbackFor=Exception.class)
web支持
-------
servlet代码
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String name=request.getParameter("name");
ApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
HelloService helloService=(HelloService) ac.getBean("helloService");
String message=helloService.sayHello(name);
request.setAttribute("message", message);
request.getRequestDispatcher("/hello.jsp").forward(request, response);
}
web.xml代码
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlet.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
spring-struts代码【默认自动装配】
<bean id="helloService" class="service.impl.HelloServiceImpl">
<property name="perfix" value="Hello"></property>
</bean>
<bean id="helloAction" class="action.HelloAction">
<property name="helloService" ref="helloService"></property>
</bean>
<package name="test" extends="struts-default">
<action name="hello" class="helloAction">
<result>/success.jsp</result>
</action>
</package>
------------------------
开发:
需要的jar文件:
commons-attributes-api.jar
commons-attributes-compiler.jar
commons-logging.jar
log4j-1.2.14.jar
spring-beans.jar
spring-context.jar
spring-core.jar
低版本 xml文件不提示:是因为myeclipse不知道xsd文件,需要添加
配置文件:
bean中id 和 name 区别【id不可以重复,name可以重复】
Spring培训笔记
最新推荐文章于 2024-01-01 08:52:59 发布