SSH(三)

在Spring中引用属性文件:
    优点:
        1.防止随意更改jdbc的连接
        2.给不懂代码的人使用
    步骤:
        1.数据库连接信息写在属性文件中
        范例:#jdbc.properties   

1  jdbc.driver = com.mysql.jdbc.Driver
2  jdbc.url = jdbc:mysql://localhost/db
3  jdbc.username = root
4  jdbc.password = root


        2.采用PropertyPlaceholderConfigurer可以引入属性文件,在Spring配置文件中采用诸如${jdbc.url}的方式引用属性值

        3.PropertyPlaceholderConfigurer的配置用到了List类型属性
        
Spring自动装配:
    1.定义:Spring可以根据属性类型、名称等自动进行注入
    2.使用方法:设置<bean>元素的autowire属性
        a.autowire属性取值:
            取值                            说明
             no                默认值。Spring 默认不进行自动装配,必须显式指定依赖对象
             byName            根据属性名自动装配。Spring 自动查找与属性名相同的id,如果找到,则自动注入,否则什么都不做
             byType            根据属性的类型自动装配。Spring 自动查找与属性类型相同的Bean,如果刚好找到★唯一★的那个,则自动注入;如果找到多个与属性类型相同的Bean,则抛出异常;如果没找              到,就什么也不做
             constructor    和byType 类似,不过它针对构造方法。如果 Spring 找到一个Bean和构造方法的参数类型相匹配,则通过构造注入该依赖对象;如果找不到,将抛出异常
        b.可以为<beans>元素设置default-autowire属性,影响全局
        c.<bean>节点上autowire的设置可以覆盖全局设置
    3.一般情况下,使用byName的方式更合适。Spring3推荐使用带参构造或者使用在setXxx方法上使用@Required注解

    4.注意:自动装配使得配置文件可以非常简洁,但同时也造成组件之间的依赖关系不明确,容易引发一些潜在的错误,在实际项目中要谨慎使用

拆分配置文件 -- 拆分策略
    1.公用配置+每个系统模块一个单独配置文件(包含dao、service、action)
    2.公用配置+DAO Bean配置+业务逻辑Bean配置+Action Bean配置
    3.两种策略各有特色,适用于不同场合

    方法:
        a.配制Spring集成时:
            1)配制ContextLoadListener的contextConfigLocation属性
            2)配置多个配置文件用逗号隔开
            3)使用通配符
        b.使用<import  resource="xxx.xml"/>方式

使用注解实现IoC:
    1.注解方式将Bean的定义信息和Bean实现类结合在一起
    2.Spring提供的注解:
        @Component
        @Repository    :用于标注DAO类
        @Service    :用于标注业务类
        @Controller    :用于标注控制器类
    范例:

1 @Repository("userDao")
2 public class UserDaoImpl implements UserDao {
3 4 }

    等效:与在XML配置文件中编写

1 <bean id="userDao" class="com.xuetang9.dao.impl.UserDaoImpl" /> 


    3.使用@Autowired注解实现Bean的自动装配
        a.默认按类型匹配
        b.可以使用@Qualifier指定Bean的名称
    范例:
    a.可以对类的成员变量进行标注 

1 @Service("userService")
2 public class UserServiceImpl implements UserService {
3         @Autowired
4         @Qualifier("userDao")
5         private UserDao userDao;
6         ……
7 }


    b.也可以对方法的入参进行标注 

1  @Service("userService")
2   public class UserServiceImpl implements UserService {
3         private UserDao userDao;
4         @Autowired
5         public void setUserDao(UserDao userDao) {
6            this.userDao = userDao;
7         }
8    }

   
    4.使用@Scope注解指定Bean的作用域
    范例:

1  @Scope("prototype")
2  @Service("userService")
3   public class UserService implements UserService {
4         ……
5   }

 
    5.使用注解信息启动Spring容器
    范例:

1  <beans xmlns="http://www.springframework.org/schema/beans"
2         xmlns:context="http://www.springframework.org/schema/context"
3         xsi:schemaLocation="……
4         http://www.springframework.org/schema/context        
5         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
6         <!-- 扫描包中注解标注的类 -->
7         <!-- 指定需要扫描的基类包,多个包可用逗号隔开 -->
8         <context:component-scan base-package="com.xuetang9.demo.service, com.xuetang9.demo.dao" />
9  </beans>


使用注解实现事务处理:
    1.在Spring配置文件中配置事务管理类,并添加对注解配置的事务的支持
    范例:  

1 <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
2         <property name="sessionFactory" ref="sessionFactory" />
3 </bean>
4 <tx:annotation-driven transaction-manager="txManager" />


    2.使用@Transactional为方法添加事务支持
    范例:

1  public class UserServiceImpl implements UserService {
2         @Transactional(readOnly=true)
3         public User login(User user){
4             ......
5         }
6   }

  
    3.@Transactional属性
    属性                        类型                                                                说明
    propagation                枚举型:Propagation                                        可选的传播性设置。使用举例:@Transactional(propagation=Propagation.REQUIRES_NEW)
    isolation                枚举型:Isolation                                        可选的隔离性级别。使用举例:@Transactional(isolation=Isolation.READ_COMMITTED)
    readOnly                布尔型                                                    是否为只读型事务。使用举例:@Transactional(readOnly=true)
    timeout                    sint型(以秒为单位)                                    事务超时。使用举例:Transactional(timeout=10)
    rollbackFor                一组 Class 类的实例,必须是Throwable的子类            一组异常类,遇到时 必须回滚。使用举例:@Transactional(rollbackFor={SQLException.class}),多个异常用逗号隔开
    rollbackForClassName    一组 Class 类的名字,必须是Throwable的子类            一组异常类名,遇到时 必须回滚。使用举例:@Transactional(rollbackForClassName={"SQLException"}),多个异常用逗号隔开
    noRollbackFor            一组 Class 类的实例,必须是Throwable的子类            一组异常类,遇到时 必须不回滚
    noRollbackForClassName    一组 Class 类的名字,必须是Throwable的子类            一组异常类名,遇到时 必须不回滚
    
范例:
1.hibernate的配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE hibernate-configuration PUBLIC
 3         "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
 4         "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
 5 <hibernate-configuration>
 6     <session-factory>
 7         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
 8         <property name="hibernate.connection.password">root</property>
 9         <property name="hibernate.connection.url">jdbc:mysql://localhost/hibernatedb</property>
10         <property name="hibernate.connection.username">root</property>
11         <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
12     </session-factory>
13 </hibernate-configuration>


2.Struts的配置文件

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd" >
 3 <struts>
 4     <package name="default" namespace="/" extends="struts-default">
 5         <action name="login" class="com.Elastic.SpringDemo4.ivy.action.UserAction" method="login">
 6             <result name="success">/index.jsp</result>
 7             <result name="error">/error.jsp</result>
 8         </action>
 9     </package>
10 </struts>


3.Spring的配置文件
a1.spring与hibernate的配置文件分离 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12 
13     <!-- 配置SessionFactory -->
14     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
15         <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
16     </bean>
17     <!-- 配置事务 -->
18     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
19         <property name="sessionFactory" ref="sessionFactory"></property>
20     </bean>
21     <tx:advice id="tx" transaction-manager="transactionManager">
22         <tx:attributes>
23             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
24             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
25         </tx:attributes>
26     </tx:advice>
27     <aop:config>
28         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
29         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
30     </aop:config>
31 </beans>


a2.spring与hibernate集成 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12 
13     <!-- 配置DataSource,c3p0的方式配置数据源 -->
14     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
15         <property name="user" value="root"></property>
16         <property name="password" value="root"></property>
17         <property name="jdbcUrl" value="jdbc:mysql://localhost/hibernatedb"></property>
18         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
19         <property name="initialPoolSize" value="10"></property>
20         <property name="minPoolSize" value="5"></property>
21         <property name="maxPoolSize" value="100"></property>
22         <property name="acquireIncrement" value="3"></property>
23         <property name="acquireRetryAttempts" value="3"></property>
24         <property name="acquireRetryDelay" value="5"></property>
25         <property name="idleConnectionTestPeriod" value="60"></property>
26     </bean>
27 
28     <!-- 配置SessionFactory -->
29     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
30         <property name="dataSource" ref="dataSource"></property>
31         <property name="hibernateProperties">
32             <props>
33                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
34                 <prop key="show_sql">true</prop>
35                 <prop key="format_sql">true</prop>
36             </props>
37         </property>
38         <property name="mappingLocations">
39             <list>
40                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
41             </list>
42         </property>
43         <!-- 加载持久化类也可以使用<property name="packagesToScan" value="com.Elastic.SpringDemo4.ivy.entity" /> -->
44         <!-- <property name="annotatedClasses">
45             <list>
46                 <value>com.Elastic.SpringDemo4.ivy.entity.User</value>
47             </list>
48         </property> -->
49     </bean>
50     <!-- 配置事务 -->
51     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
52         <property name="sessionFactory" ref="sessionFactory"></property>
53     </bean>
54     <tx:advice id="tx" transaction-manager="transactionManager">
55         <tx:attributes>
56             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
57             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
58         </tx:attributes>
59     </tx:advice>
60     <aop:config>
61         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
62         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
63     </aop:config>
64 </beans>


a3.在Spring中引用属性文件 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12     <!-- 配置属性文件的读取 -->
13     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
14         <property name="location" value="classpath:jdbc.properties"></property>
15     </bean>
16 
17     <!-- 配置DataSource -->
18     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
19         <property name="user" value="${jdbc.username}"></property>
20         <property name="password" value="${jdbc.password}"></property>
21         <property name="jdbcUrl" value="${jdbc.url}"></property>
22         <property name="driverClass" value="${jdbc.driver}"></property>
23         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
24         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>
25         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
26         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
27         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>
28         <property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"></property>
29         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>
30     </bean>
31 
32     <!-- 配置SessionFactory -->
33     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
34         <property name="dataSource" ref="dataSource"></property>
35         <property name="hibernateProperties">
36             <props>
37                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
38                 <prop key="show_sql">true</prop>
39                 <prop key="format_sql">true</prop>
40             </props>
41         </property>
42         <property name="mappingLocations">
43             <list>
44                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
45             </list>
46         </property>
47     </bean>
48     <!-- 配置事务 -->
49     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
50         <property name="sessionFactory" ref="sessionFactory"></property>
51     </bean>
52     <tx:advice id="tx" transaction-manager="transactionManager">
53         <tx:attributes>
54             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
55             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
56         </tx:attributes>
57     </tx:advice>
58     <aop:config>
59         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
60         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
61     </aop:config>
62 </beans>


a4.当有多个Spring的配置文件时 -- applicationContext.xml
方法二:applicationContext配置中用,<import resource="">

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xsi:schemaLocation="http://www.springframework.org/schema/beans
 7         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 8         http://www.springframework.org/schema/aop
 9         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd">
12     <!-- 配置属性文件的读取 -->
13     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
14         <property name="location" value="classpath:jdbc.properties"></property>
15     </bean>
16 
17     <!-- 配置DataSource -->
18     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
19         <property name="user" value="${jdbc.username}"></property>
20         <property name="password" value="${jdbc.password}"></property>
21         <property name="jdbcUrl" value="${jdbc.url}"></property>
22         <property name="driverClass" value="${jdbc.driver}"></property>
23         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
24         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>
25         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
26         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
27         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>
28         <property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"></property>
29         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>
30     </bean>
31 
32     <!-- 配置SessionFactory -->
33     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
34         <!-- <property name="configLocation" value="classpath:hibernate.cfg.xml"></property> -->
35         <property name="dataSource" ref="dataSource"></property>
36         <property name="hibernateProperties">
37             <props>
38                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
39                 <prop key="show_sql">true</prop>
40                 <prop key="format_sql">true</prop>
41             </props>
42         </property>
43         <property name="mappingLocations">
44             <list>
45                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
46             </list>
47         </property>
48     </bean>
49     <!-- 配置事务 -->
50     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
51         <property name="sessionFactory" ref="sessionFactory"></property>
52     </bean>
53     <tx:advice id="tx" transaction-manager="transactionManager">
54         <tx:attributes>
55             <tx:method name="search*" propagation="REQUIRED" read-only="true" timeout="5"/>
56             <tx:method name="create*" propagation="REQUIRED" rollback-for="java.lang.Exception"/>
57         </tx:attributes>
58     </tx:advice>
59     <aop:config>
60         <aop:pointcut id="txpointcut" expression="execution(* com.Elastic.SpringDemo4.ivy.service..*.*(..))" />
61         <aop:advisor advice-ref="tx" pointcut-ref="txpointcut"/>
62     </aop:config>
63     
64     <!-- DAO -->
65     <import resource="Spring-DAO.xml"/>
66     
67     <!-- Service -->
68     <import resource="Spring-Service.xml"/>
69 </beans>


a5.使用注解 -- applicationContext.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xmlns:tx="http://www.springframework.org/schema/tx"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xsi:schemaLocation="http://www.springframework.org/schema/beans
 8         http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 9         http://www.springframework.org/schema/aop
10         http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
11         http://www.springframework.org/schema/tx
12         http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
13         http://www.springframework.org/schema/context
14         http://www.springframework.org/schema/context/spring-context-3.2.xsd">
15     <!-- 配置属性文件的读取 -->
16     <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
17         <property name="location" value="classpath:jdbc.properties"></property>
18     </bean>
19 
20     <!-- 配置DataSource -->
21     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
22         <property name="user" value="${jdbc.username}"></property>
23         <property name="password" value="${jdbc.password}"></property>
24         <property name="jdbcUrl" value="${jdbc.url}"></property>
25         <property name="driverClass" value="${jdbc.driver}"></property>
26         <property name="initialPoolSize" value="${jdbc.initialPoolSize}"></property>
27         <property name="minPoolSize" value="${jdbc.minPoolSize}"></property>
28         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
29         <property name="acquireIncrement" value="${jdbc.acquireIncrement}"></property>
30         <property name="acquireRetryAttempts" value="${jdbc.acquireRetryAttempts}"></property>
31         <property name="acquireRetryDelay" value="${jdbc.acquireRetryDelay}"></property>
32         <property name="idleConnectionTestPeriod" value="${jdbc.idleConnectionTestPeriod}"></property>
33     </bean>
34 
35     <!-- 配置SessionFactory -->
36     <bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
37         <property name="dataSource" ref="dataSource"></property>
38         <property name="hibernateProperties">
39             <props>
40                 <prop key="dialect">org.hibernate.dialect.MySQLDialect</prop>
41                 <prop key="show_sql">true</prop>
42                 <prop key="format_sql">true</prop>
43             </props>
44         </property>
45         <property name="mappingLocations">
46             <list>
47                 <value>classpath:com/Elastic/SpringDemo4/ivy/entity/*.hbm.xml</value>
48             </list>
49         </property>
50     </bean>
51     
52     <!-- 配置事务 -->
53     <bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
54         <property name="sessionFactory" ref="sessionFactory"></property>
55     </bean>
56     <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
57     
58     <!-- 使用注解配置DAOService -->
59     <context:component-scan base-package="com.Elastic.SpringDemo4.ivy"></context:component-scan>        
60 </beans>


b.Spring-DAO.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7 
 8     <bean id="userDao" class="com.Elastic.SpringDemo4.ivy.dao.impl.UserDaoImpl">
 9         <property name="sessionFactory" ref="sessionFactory"></property>
10     </bean>
11 
12 </beans>


b2.Spring自动配置 -- Spring-DAO.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7 
 8     <bean id="userDao" class="com.Elastic.SpringDemo4.ivy.dao.impl.UserDaoImpl" autowire="byName">
 9     </bean>
10 </beans>


c.Spring-Service.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7 
 8     <bean id="userService" class="com.Elastic.SpringDemo4.ivy.service.impl.UserServiceImpl">
 9         <property name="userDao" ref="userDao"></property>
10     </bean>
11 </beans>


c2.Spring自动配置 -- Spring-Service.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4     xmlns:aop="http://www.springframework.org/schema/aop"
 5     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
 6         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">
 7 
 8     <bean id="userService" class="com.Elastic.SpringDemo4.ivy.service.impl.UserServiceImpl" autowire="byName">
 9     </bean>
10 </beans>


4.动态Java项目的配置
a.web.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 3     <display-name>SpringDemo4_ivy</display-name>
 4     <welcome-file-list>
 5         <welcome-file>index.html</welcome-file>
 6         <welcome-file>index.htm</welcome-file>
 7         <welcome-file>index.jsp</welcome-file>
 8         <welcome-file>default.html</welcome-file>
 9         <welcome-file>default.htm</welcome-file>
10         <welcome-file>default.jsp</welcome-file>
11     </welcome-file-list>
12     
13     <!-- 配置Spring文件的位置 -->
14     <context-param>
15         <param-name>contextConfigLocation</param-name>
16         <param-value>classpath:applicationContext.xml</param-value>
17     </context-param>
18     
19     <!-- 配置Spring监听器 -->
20     <listener>
21         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
22     </listener>
23     
24     <!-- OpenSessionInView -->
25     <filter>
26         <filter-name>OpenSessionInView</filter-name>
27         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
28     </filter>
29     <filter-mapping>
30         <filter-name>OpenSessionInView</filter-name>
31         <url-pattern>/*</url-pattern>
32     </filter-mapping>
33     
34     <!-- 配置Struts2核心过滤器 -->
35     <filter>
36         <filter-name>Struts2</filter-name>
37         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
38     </filter>
39     <filter-mapping>
40         <filter-name>Struts2</filter-name>
41         <url-pattern>/*</url-pattern>
42     </filter-mapping>
43     
44     <!-- 设置session过期时间(单位:分钟) -->
45     <session-config>
46         <session-timeout>20</session-timeout>
47     </session-config>
48     
49 </web-app>


b.当有多个Spring的配置文件时
方法一:context-param配置中用逗号隔开

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
 3     <display-name>SpringDemo4_ivy</display-name>
 4     <welcome-file-list>
 5         <welcome-file>index.html</welcome-file>
 6         <welcome-file>index.htm</welcome-file>
 7         <welcome-file>index.jsp</welcome-file>
 8         <welcome-file>default.html</welcome-file>
 9         <welcome-file>default.htm</welcome-file>
10         <welcome-file>default.jsp</welcome-file>
11     </welcome-file-list>
12     
13     <!-- 配置Spring文件的位置 -->
14     <context-param>
15         <param-name>contextConfigLocation</param-name>
16         <param-value>classpath:applicationContext.xml,classpath:Spring-*.xml</param-value>
17     </context-param>
18     
19     <!-- 配置Spring监听器 -->
20     <listener>
21         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
22     </listener>
23     
24     <!-- OpenSessionInView -->
25     <filter>
26         <filter-name>OpenSessionInView</filter-name>
27         <filter-class>org.springframework.orm.hibernate3.support.OpenSessionInViewFilter</filter-class>
28     </filter>
29     <filter-mapping>
30         <filter-name>OpenSessionInView</filter-name>
31         <url-pattern>/*</url-pattern>
32     </filter-mapping>
33     
34     <!-- 配置Struts2核心过滤器 -->
35     <filter>
36         <filter-name>Struts2</filter-name>
37         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
38     </filter>
39     <filter-mapping>
40         <filter-name>Struts2</filter-name>
41         <url-pattern>/*</url-pattern>
42     </filter-mapping>
43     
44     <!-- 设置session过期时间(单位:分钟) -->
45     <session-config>
46         <session-timeout>20</session-timeout>
47     </session-config>
48     
49 </web-app>


5.属性文件
a.jdbc.properties

 1 jdbc.username=root
 2 jdbc.password=root
 3 jdbc.url=jdbc:mysql://localhost/hibernatedb
 4 jdbc.driver=com.mysql.jdbc.Driver
 5 
 6 # c3p0
 7 jdbc.initialPoolSize=10
 8 jdbc.minPoolSize=5
 9 jdbc.maxPoolSize=100
10 jdbc.acquireIncrement=3
11 jdbc.acquireRetryAttempts=3
12 jdbc.acquireRetryDelay=5
13 jdbc.idleConnectionTestPeriod=60


6.实体类及其配置文件
a.User类

 1 package com.Elastic.SpringDemo4.ivy.entity;
 2 
 3 import java.io.Serializable;
 4 
 5 public class User implements Serializable{
 6     private String loginName;
 7     private String loginPass;
 8     
 9     public String getLoginName() {
10         return loginName;
11     }
12     public void setLoginName(String loginName) {
13         this.loginName = loginName;
14     }
15     public String getLoginPass() {
16         return loginPass;
17     }
18     public void setLoginPass(String loginPass) {
19         this.loginPass = loginPass;
20     }
21     
22 }


b.User.hbm.xml

 1 <?xml version="1.0"?>
 2 <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
 3 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
 4 <!-- Generated 2016-7-8 16:52:24 by Hibernate Tools 3.4.0.CR1 -->
 5 <hibernate-mapping>
 6     <class name="com.Elastic.SpringDemo4.ivy.entity.User" table="user">
 7         <id name="loginName" type="java.lang.String">
 8             <column name="userName" />
 9             <generator class="assigned" />
10         </id>
11         <property name="loginPass" type="java.lang.String">
12             <column name="passWord" />
13         </property>
14     </class>
15 </hibernate-mapping>


7.dao包
a.UserDao接口

1 package com.Elastic.SpringDemo4.ivy.dao;
2 
3 import java.io.Serializable;
4 
5 import com.Elastic.SpringDemo4.ivy.entity.User;
6 
7 public interface UserDao {
8     User findById(Serializable id);
9 }


8.dao.impl包
a1.UserDaoImpl

 1 package com.Elastic.SpringDemo4.ivy.dao.impl;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9 
10 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
11 import com.Elastic.SpringDemo4.ivy.entity.User;
12 
13 public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
14     
15     @Override
16     public User findById(Serializable id) {
17         return this.getHibernateTemplate().get(User.class, id);
18     }
19 }


a2.使用注解 -- UserDaoImpl

 1 package com.Elastic.SpringDemo4.ivy.dao.impl;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9 
10 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
11 import com.Elastic.SpringDemo4.ivy.entity.User;
12 
13 @Repository
14 public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
15     
16     @Autowired
17     public UserDaoImpl(SessionFactory sessionFactory) {
18         super.setSessionFactory(sessionFactory);
19     }
20     
21     @Override
22     public User findById(Serializable id) {
23         return this.getHibernateTemplate().get(User.class, id);
24     }
25 }


b.使用注解 -- TestUserDaoImpl

 1 package com.Elastic.SpringDemo4.ivy.dao.impl;
 2 
 3 import java.io.Serializable;
 4 
 5 import org.hibernate.SessionFactory;
 6 import org.springframework.beans.factory.annotation.Autowired;
 7 import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9 
10 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
11 import com.Elastic.SpringDemo4.ivy.entity.User;
12 
13 @Repository
14 public class TestUserDaoImpl extends HibernateDaoSupport implements UserDao {
15 
16     @Autowired
17     public TestUserDaoImpl(SessionFactory sessionFactory) {
18         super.setSessionFactory(sessionFactory);
19     }
20     
21     @Override
22     public User findById(Serializable id) {
23         return null;
24     }
25 }


9.service包
a.UserService接口

1 package com.Elastic.SpringDemo4.ivy.service;
2 
3 import com.Elastic.SpringDemo4.ivy.entity.User;
4 
5 public interface UserService {
6     public User search(String name, String pass);
7 }


10.service.impl包
a.UserServiceImpl

 1 package com.Elastic.SpringDemo4.ivy.service.impl;
 2 
 3 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
 4 import com.Elastic.SpringDemo4.ivy.entity.User;
 5 import com.Elastic.SpringDemo4.ivy.service.UserService;
 6 
 7 public class UserServiceImpl implements UserService {
 8     private UserDao userDao;
 9 
10     public UserDao getUserDao() {
11         return userDao;
12     }
13 
14     public void setUserDao(UserDao userDao) {
15         this.userDao = userDao;
16     }
17 
18     @Override
19     public User search(String name, String pass) {
20         User user = userDao.findById(name);
21         if (null != user && user.getLoginPass().equals(pass)) {
22             return user;
23         }
24         return null;
25     }
26 }


a2.使用注解 -- UserServiceImpl

 1 package com.Elastic.SpringDemo4.ivy.service.impl;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.beans.factory.annotation.Qualifier;
 5 import org.springframework.stereotype.Service;
 6 import org.springframework.transaction.annotation.Propagation;
 7 import org.springframework.transaction.annotation.Transactional;
 8 
 9 import com.Elastic.SpringDemo4.ivy.dao.UserDao;
10 import com.Elastic.SpringDemo4.ivy.entity.User;
11 import com.Elastic.SpringDemo4.ivy.service.UserService;
12 
13 @Service("userService")
14 @Transactional(propagation=Propagation.REQUIRED,rollbackFor={Exception.class,RuntimeException.class})
15 public class UserServiceImpl implements UserService {
16     //方法一
17     @Autowired
18     @Qualifier("userDaoImpl")
19     private UserDao userDao;
20 
21     //方法二
22     /*public UserDao getUserDao() {
23         return userDao;
24     }
25 
26     @Autowired
27     @Qualifier("testUserDaoImpl")
28     public void setUserDao(UserDao userDao) {
29         this.userDao = userDao;
30     }*/
31 
32 //    @Transactional(propagation=Propagation.REQUIRED,readOnly=true,timeout=3,rollbackFor={Exception.class,RuntimeException.class})
33     @Transactional(timeout=3)
34     @Override
35     public User search(String name, String pass) {
36         try {
37             Thread.sleep(4000);
38         } catch (InterruptedException e) {
39             e.printStackTrace();
40         }
41         
42         User user = userDao.findById(name);
43         if (null != user && user.getLoginPass().equals(pass)) {
44             return user;
45         }
46         return null;
47     }
48     
49     @Transactional
50     public void test() {
51         userDao.findById("");
52     }
53 }


11.action包
a.UserAction

 1 package com.Elastic.SpringDemo4.ivy.action;
 2 
 3 import com.Elastic.SpringDemo4.ivy.entity.User;
 4 import com.Elastic.SpringDemo4.ivy.service.UserService;
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 public class UserAction extends ActionSupport {
 8     private UserService userService;
 9     private User user;
10 
11     public UserService getUserService() {
12         return userService;
13     }
14 
15     public void setUserService(UserService userService) {
16         this.userService = userService;
17     }
18 
19     public User getUser() {
20         return user;
21     }
22 
23     public void setUser(User user) {
24         this.user = user;
25     }
26 
27     public String login() {
28         User loginUser =  userService.search(user.getLoginName(), user.getLoginPass());
29         if (null == loginUser) {
30             return ERROR;
31         }
32         return SUCCESS;
33     }
34 }



原文地址:https://www.cnblogs.com/ivy-xu/p/5656780.html