<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="https://www.springframework.org/schema/beans"
xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
xmlns:context="https://www.springframework.org/schema/context"
xmlns:aop="https://www.springframework.org/schema/aop"
xmlns:tx="https://www.springframework.org/schema/tx"
xsi:schemaLocation="
https://www.springframework.org/schema/beans https://www.springframework.org/schema/beans/spring-beans-2.5.xsd
https://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context-2.5.xsd
https://www.springframework.org/schema/tx https://www.springframework.org/schema/tx/spring-tx-2.5.xsd
https://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<!-- 1. 開啟註解掃描與 AOP -->
<context:annotation-config/>
<context:component-scan base-package="com.hkwy"/>
<aop:aspectj-autoproxy/>
<!-- 2. C3P0 數據源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/spring1"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
<property name="initialSize" value="1"/>
<property name="maxActive" value="500"/>
<property name="maxIdle" value="2"/>
<property name="minIdle" value="1"/>
<property name="maxWait" value="1000"/>
</bean>
<!-- 3. Hibernate 3 Annotation SessionFactory -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="packagesToScan" value="com.hkwy.entity"/>
<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>
<prop key="hibernate.hbm2ddl.auto">update</prop>
</props>
</property>
</bean>
<!-- 4. 事務管理器 + AOP 聲明式事務 -->
<bean id="txmanager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
<aop:config>
<aop:pointcut expression="execution(* com.hkwy.dao.*.*(..))" id="aoph"/>
<aop:advisor advice-ref="txadvice" pointcut-ref="aoph"/>
</aop:config>
<tx:advice id="txadvice" transaction-manager="txmanager">
<tx:attributes>
<tx:method name="*" propagation="REQUIRED"/>
</tx:attributes>
</tx:advice>
</beans>
context:component-scan 替代繁瑣 Bean 定義。packagesToScan 自動發現 @Entity,無需 .hbm.xml。execution(* com.hkwy.dao.*.*(..)) 精準切 DAO 層,Service 層同理。propagation="REQUIRED" 滿足大多數業務,查詢類可單獨配 read-only="true"。Spring 3.1+ 建議改用 spring-beans-3.2.xsd、Hibernate 4/5 遷移至 LocalSessionFactoryBean + hibernate4/5 包,C3P0 推薦換 HikariCP 或 Druid。