Spring培训笔记

来源:互联网 发布:软件研发规范 编辑:程序博客网 时间:2024/06/06 20:33
Spring负责整个应用是业务逻辑组件框架目的:程序结构良好,简化开发必须要会 很重要Spring开发包dist/spring.jar  spring核心jar包spring-src.zipmodules/目录下将 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配置实例化时机,默认预先实例化实现类:加载资源的相对路径不同ClassPathXmlApplicationContextFileSystemXmlApplicationContext配置装备/注入装配的属性的类型简单值: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 PropertyEditorSupport2、用后处理 去添加这些规则<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();//关闭虚拟时销毁容器中的Beanac.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类实现了代理接口),使用动态代理模式实现AOPBean类没有实现接口Spring使用CGLib类生成代理对象该对象是目标对象的子类对象因此Bean不能是final类目标类如果是final类,并且没有实现代理接口,不能是用AOPSpring 1.x FactoryBean1、通知(Advice)通知类型  接口Around环绕通知MethodInterceptorBefore前置通知MethodBeforeAdviceAfter后置通知AfterReturningAdviceThrows异常通知ThrowsAdvice2、ProxyFactoryBeanAdvisorAdvisor=Advice+Pointcut通知   切入点//自定义切入点public class MyPointcut implements Pointcutpublic class LogAdvisor implements PointcutAdvisor预定义切入点org.springframework.aop.support包下NameMatchMethodPointcutAdvisor自动代理多个目标对象使用相同的切面Spring AOP 2.x 后处理特点:非侵入性,完全基于xml配置,使用AspectJ的切点表达式<beansxmlns="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.xsdhttp://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 orSomeService doSome    OtherServiceexecution(* aop8.SomeServiceImpl.doSome(..)) or within(aop8.OtherServiceImpl)Advicebefore after:after-returning after-throwingaround 对方法有以下要求:1.返回类型是Object2.参数ProceedingJoinPoint3.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,采用模板模式模板类:包装了持久化技术的操作,简化编程的重复代码提供与平台无关的异常转换RuntimeExceptionDateIntegrityViolationException违反了约束DateAccessResourceFailureException数据访问资源失败InvalidDateAccessResourceUsageException使用错误的sql语句回调接口:暴露底层api数据源配置:方式一:Spring内置的数据源 DriverManagerDateSource方式二:使用第三方DataSource org.apache.commons.dbcp.BasicDataSource方式三:JNDI数据源JDBC支持1、使用JdbcTemplate配置dataSource-》jdbcTemplate->Dao使用 Dao注入JdbcTemplate方法:execute query queryXxx update2、使用JdbcDaoSupport配置dataSource->Dao使用Dao继承JdbcDaoSupport使用getJdbcTemplate()获得模板Hibernate支持1、使用HibernateTemplate配置:dataSource->sessionFactory->hibernateTemplate->Dao使用:Dao注入HibernateTemplate2、使用HibernateDaoSupport配置:dataSource->sessionFactory->Dao使用:Dao继承HibernateDaoSupport使用getHibernateTemplate()3、本地Hibernate配置:dataSource->sessionFactory->Dao配置一个后处理Bean使用:Dao注入SessionFactory使用sessionFactory.getCurrentSession()获得Sessionspring开发包lib/dom4j/dom4j.jarj2ee/jta.jarjakarta-commons/commons-pool.jarcommons-collections.jarantlr/antrl-2.7.6.jar事务支持【三种方法】事务管理器TransactionManagerjdbcorg.springframwork.jdbc.datasource.DataSourceTransactionManagerdataSource->transactionManagerhibernateorg.springframework.orm.hibernate.HibernateTransactionManagersessionFactory->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.jarcommons-attributes-compiler.jarcommons-logging.jarlog4j-1.2.14.jarspring-beans.jarspring-context.jarspring-core.jar低版本 xml文件不提示:是因为myeclipse不知道xsd文件,需要添加配置文件:bean中id 和 name 区别【id不可以重复,name可以重复】

原创粉丝点击