spring 的 applicationcontext.xml
以下是详解Spring的applicationContext.xml文件代码:
<!-- 头文件,主要注意一下编码 -->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">
<beans>
<!-- 建立数据源 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<!-- 数据库驱动,我这里使用的是Mysql数据库 -->
<property name="driverClassName">
<value>com.mysql.jdbc.Driver</value>
</property>
<!-- 数据库地址,这里也要注意一下编码,不然乱码可是很郁闷的哦! -->
<property name="url">
<value>
jdbc:mysql://localhost:3306/tie?useUnicode=true&characterEncoding=utf-8
</value>
</property>
<!-- 数据库的用户名 -->
<property name="username">
<value>root</value>
</property>
<!-- 数据库的密码 -->
<property name="password">
<value>123</value>
</property>
</bean>
<!-- 把数据源注入给Session工厂 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref bean="dataSource" />
</property>
<!-- 配置映射文件 -->
<property name="mappingResources">
<list>
<value>com/alonely/vo/User.hbm.xml</value>
</list>
</property>
</bean>
<!-- 把Session工厂注入给hibernateTemplate -->
<!-- 解释一下hibernateTemplate:hibernateTemplate提供了很多方便的方法,在执行时自动建立 HibernateCallback 对象,例如:load()、get()、save、delete()等方法。 -->
<bean id="hibernateTemplate"
class="org.springframework.orm.hibernate3.HibernateTemplate">
<constructor-arg>
<ref local="sessionFactory" />
</constructor-arg>
</bean>
<!-- 把DAO注入给Session工厂 -->
<bean id="userDAO" class="com.alonely.dao.UserDAO">
<property name="sessionFactory">
<ref bean="sessionFactory" />
</property>
</bean>
<!-- 把Service注入给DAO -->
<bean id="userService" class="com.alonely.service.UserService">
<property name="userDAO">
<ref local="userDAO" />
</property>
</bean>
<!-- 把Action注入给Service -->
<bean name="/user" class="com.alonely.struts.action.UserAction">
<property name="userService">
<ref bean="userService" />
</property>
</bean>
</beans>
下面是Struts+Spring+Hibernate的中 applicationContext.xml配置文件分析
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">
<!-- 此配置文件整合了Spring和hibernate的配置文件!采用BasicDataSource注入到hibernate sessionFactory中,以得到数据库连接 -->
<!-- dbcp相关参数配置见 http://marzian.blog.163.com/blog/static/266863120086845013920 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
<property name="driverClassName">
<value>oracle.jdbc.driver.OracleDriver</value>
</property>
<property name="url">
<value>jdbc:oracle:thin:@10.18.100.52:1521:dxcp1</value>
</property>
<property name="username">
<value>newgspls</value>
</property>
<property name="password">
<value>newgspls</value>
</property>
<property name="initialSize">
<value>1</value>
</property>
<property name="maxActive">
<value>60</value>
</property>
<property name="minIdle">
<value>1</value>
</property>
<property name="maxWait">
<value>6000</value>
</property>
<property name="validationQuery">
<value>select user from dual</value>
</property>
</bean>
<!--从连接池中抽取出本地数据库JDBC对象 几种JDBC对象抽取器,可根据不同的应用服务器进行调整
WebLogic:WebLogicNativeJdbcExtractor
WebSphere:WebSphereNativeJdbcExtractor
JBoss:JBossNativeJdbcExtractor
-->
<bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true"></bean>
<!-- s可以使用Spring的 JDBC帮助类 jdbcTemplate-->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource"><ref bean="dataSource"/></property>
</bean>
<!--Spring 提供了两种LobHandler 用于处理Blob数据
DefaultLobHandler:适用于大部分的数据库,如SqlServer,MySQL,对Oracle 10g也适用,但不适用于Oracle9i
oracleLobHandler:适用于Oracle 9i和Oracle 10g。
-->
<bean id="lobHandler" class="org.springframework.jdbc.support.lob.OracleLobHandler" lazy-init="true">
<property name="nativeJdbcExtractor">
<ref local="nativeJdbcExtractor" />
</property>
</bean>
<!--Hibernate Session工厂配置-->
<bean id="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource">
<ref local="dataSource"/>
</property>
<property name="lobHandler" ref="lobHandler"/>
<property name="mappingResources">
<list>
<!-- hibernate实体映射文件!即生成的 *.hbm.xml-->
<value>com/dao/hibernate/xml/MaintenanceWork.hbm.xml</value>
<value>com/dao/hibernate/xml/SignIn.hbm.xml</value>
</list>
</property>
<!-- sessionFactory相关配置 -->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
<!--采用Hibernate2.0的HSql解释器,解决了中文问题-->
<prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop>
<!--打开Query Cache开关,需要Cache的query需要单独配置-->
<prop key="hibernate.cache.use_query_cache">true</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
</props>
</property>
</bean>
<!--事务管理器配置-->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
<!--AOP 事务配置-->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<!-- the transactional semantics... -->
<tx:attributes>
<!-- all methods starting with 'get' are read-only -->
<tx:method name="get*" read-only="true"/>
<tx:method name="add*" read-only="false"/>
<tx:method name="insert*" read-only="false"/>
<tx:method name="update*" read-only="false"/>
<tx:method name="del*" read-only="false"/>
<tx:method name="audit*" read-only="false"/>
<!-- other methods use the default transaction settings (see below) -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="SysFileOperation" expression="execution(* com.biz.system.SysFilesBiz.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="SysFileOperation"/>
</aop:config>
<!-- jdbc Dao 配置 begion -->
<bean id="jdbcDao" class="com.gsww.newgspls.dao.JdbcDao">
<property name="ds">
<ref local="dataSource"/>
</property>
</bean>
<!-- 信息发布配置开始 -->
<bean id="sysInfoBiz" class="com.biz.info.SysInfoBiz">
<property name="sysInfoDao">
<ref local="sysInfoDao" />
</property>
</bean>
<bean id="sysInfoDao" class="com.dao.info.SysInfoDao">
<property name="sessionFactory">
<ref local="sessionFactory"/>
</property>
</bean>
</beans>
业务类 SysInfoBiz
在applicationContext.xml配置注入关系后,在业务类中通过set注入即可得到SysInfoDao
package com.biz.info;
/**
* @author 作者:周伟
*
* @version 创建时间:2008-7-1 下午04:11:04
*
* 类说明
*/
import java.util.List;
import com.dao.info.SysInfoDao;
import com.domain.info.SysInfo;
public class SysInfoBiz {
private SysInfoDao sysInfoDao = null;
/**
* 判断用户是否包含在已读人列表,即通过clob字段里的用户ID查看登陆用户是否已经读过
*
* @param supportTable
* @param reader
* @return
*/
public boolean isRead(SysInfo sysInfo, String reader) {
if (sysInfo.getInfoReader() != null) {
String str = sysInfo.getInfoReader();
if (str.indexOf(",") < 0) {
return (str.contains(reader));
} else {
String pstr = reader + ",";
String astr = "," + reader;
String str1 = "," + reader + ",";
return (str.startsWith(pstr) || str.endsWith(astr) || str
.contains(str1));
}
} else {
return false;
}
}
/**
* 返回信息读者个数
*
* @param supportTable
* @return
*/
public int readTime(SysInfo sysInfo) {
if (sysInfo.getInfoReader() != null) {
String str = sysInfo.getInfoReader();
String[] str1 = str.split(",");
return str1.length;
} else {
return 0;
}
}
/**
* 对未在已读人列表的读者进行添加到SupReader
*
* @param supportTable
* @param reader
* @return
*/
public boolean addReader(SysInfo sysInfo, String reader) {
if (reader != null && !reader.equals("null")
&& !isRead(sysInfo, reader)) {
if (sysInfo.getInfoReader() != null
&& !sysInfo.getInfoReader().equals("null")
&& !sysInfo.getInfoReader().equals("")) {
sysInfo.setInfoReader(sysInfo.getInfoReader() + "," + reader);
} else {
sysInfo.setInfoReader(reader);
}
try {
sysInfoDao.update(sysInfo);
} catch (Exception re) {
re.printStackTrace();
}
return true;
} else {
return false;
}
}
/**
*删除
*/
public void delete(SysInfo persistentInstance) {
sysInfoDao.delete(persistentInstance);
}
public List findAll() {
return sysInfoDao.findAll();
}
public List findByExample(SysInfo instance) {
return sysInfoDao.findByExample(instance);
}
/**
*通过id得到实体
*/
public SysInfo findById(String id) {
return sysInfoDao.findById(id);
}
/**
*保存实体
*/
public void save(SysInfo transientInstance) {
transientInstance.setFlag("1");
sysInfoDao.save(transientInstance);
}
/**
*更新实体
*/
public void update(SysInfo transientInstance) {
transientInstance.setFlag("1");
sysInfoDao.update(transientInstance);
}
public SysInfoDao getSysInfoDao() {
return sysInfoDao;
}
public void setSysInfoDao(SysInfoDao sysInfoDao) {
this.sysInfoDao = sysInfoDao;
}
public PageDAO getPageDao() {
return pageDao;
}
public void setPageDao(PageDAO pageDao) {
this.pageDao = pageDao;
}
}
SysInfoDao 连接数据库类
package com.dao.info;
/**
* @author 作者:周伟
*
* @version 创建时间:2008-7-1 下午04:11:04
*
* 类说明 信息发布公用表dao类
*/
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.gsww.newgspls.domain.info.SysInfo;
public class SysInfoDao extends HibernateDaoSupport {
/**
* 保存SysInfo实体
*
* @param transientInstance SysInfo对象
*/
public void save(SysInfo transientInstance) {
try {
getHibernateTemplate().save(transientInstance);
} catch (RuntimeException re) {
throw re;
}
}
/**
* 更新SysInfo实体
*
* @param transientInstance SysInfo对象
*/
public void update(SysInfo transientInstance) {
try {
getHibernateTemplate().update(transientInstance);
} catch (RuntimeException re) {
throw re;
}
}
/**
* 删除SysInfo实体
*
* @param transientInstance SysInfo对象
*/
public void delete(SysInfo persistentInstance) {
try {
getHibernateTemplate().delete(persistentInstance);
} catch (RuntimeException re) {
throw re;
}
}
/**
* 通过ID得到 SysInfo对象
*
* @param id 信息主键
* @return
*/
public SysInfo findById(java.lang.String id) {
try {
SysInfo instance = (SysInfo) getHibernateTemplate().get(
"com.domain.info.SysInfo", id);
return instance;
} catch (RuntimeException re) {
throw re;
}
}
}
最近碰到这个问题,在使用spring提供的JpaTemplate进行查询时,如果数据量超过100 条,查询效率就会明显降低。由于开始时使用JPA内部的双向关联,造成各实体内部关联过多,从而影响所有的操作,因此怀疑是因为JPA的关联关系所致。但 是去掉关联关系后的效果不显著。
查找spring的相关配置,发现原来关于“transactionAttributes”有问题。原来的配置如下:
<bean id="baseTransactionProxy" class="org.springframework.transaction.interceptor.TransactionProxyFactoryBean"
lazy-init="true" abstract="true">
<property name="transactionManager">
<ref bean="transactionManager" />
</property>
<property name="transactionAttributes">
<props>
<prop key="sav*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="get*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
</props>
</property>
</bean>
使用上述配置,在JPA打出的日志中显示每次查询时都要进行更新操作,查阅相关spring 的资料后发现transactionAttributes的各种属性的意义,现把资料分享如下:
PROPAGATION_REQUIRED--支持当前事务,如果当前没有事务,就新建一个事务。这是最常见的选择。
PROPAGATION_SUPPORTS--支持当前事务,如果当前没有事务,就以非事务方式执行。
PROPAGATION_MANDATORY--支持当前事务,如果当前没有事务,就抛出异常。
PROPAGATION_REQUIRES_NEW--新建事务,如果当前存在事务,把当前事务挂起。
PROPAGATION_NOT_SUPPORTED--以非事务方式执行操作,如果当前存在事务,就把当前事务挂起。
PROPAGATION_NEVER--以非事务方式执行,如果当前存在事务,则抛出异常。
PROPAGATION_NESTED--如果当前存在事务,则在嵌套事务内执行。如果当前没有事务,则进行与PROPAGATION_REQUIRED类似的操作。提高SQL语句查询速度的方法
当前所有的事务都使用“PROPAGATION_REQUIRED”属性值,并且控制事务的操作权限为只读,以保证查询时不会更新数据。根据上述 定义 “PROPAGATION_REQUIRED”属性会造成为所有的操作都创建事务,从而会出现JPA的日志中查询时也会进行更新操作的现象,也就造成了效 率的低下。将所有查询的操作改成事务类型为“PROPAGATION_NEVER”(不使用事务),则查询效率立即提升,但是此时担心一个问题:比如在一 个saveXXX()的方法中,如果方法内部使用更新、查询、再更新的操作流程,会不会造成调用查询时,由于上述配置造成的抛出异常。
另外,如果出现
〈prop key="myMethod"〉PROPAGATION_REQUIRED,readOnly,-Exception〈/prop〉
这样的配置,其中:
-Exception表示有Exception抛出时,事务回滚. -代表回滚+就代表提交
readonly 就是read only, 设置操作权限为只读,一般用于查询的方法,优化作用.
- <?xml version="1.0" encoding="UTF-8"?>
- <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
- xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p" xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
- xmlns:cache="http://www.springframework.org/schema/cache"
- xsi:schemaLocation="
- http://www.springframework.org/schema/context
- http://www.springframework.org/schema/context/spring-context.xsd
- http://www.springframework.org/schema/beans
- http://www.springframework.org/schema/beans/spring-beans.xsd
- http://www.springframework.org/schema/tx
- http://www.springframework.org/schema/tx/spring-tx.xsd
- http://www.springframework.org/schema/jdbc
- http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd
- http://www.springframework.org/schema/cache
- http://www.springframework.org/schema/cache/spring-cache-3.1.xsd
- http://www.springframework.org/schema/aop
- http://www.springframework.org/schema/aop/spring-aop.xsd
- http://www.springframework.org/schema/util
- http://www.springframework.org/schema/util/spring-util.xsd">
- <!-- 自动扫描web包 ,将带有注解的类 纳入spring容器管理 -->
- <context:component-scan base-package="com.eduoinfo.finances.bank.web"></context:component-scan>
- <!-- 引入jdbc配置文件 -->
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath*:jdbc.properties</value>
- </list>
- </property>
- </bean>
- <!-- dataSource 配置 -->
- <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
- <!-- 基本属性 url、user、password -->
- <property name="url" value="${jdbc.url}" />
- <property name="username" value="${jdbc.username}" />
- <property name="password" value="${jdbc.password}" />
- <!-- 配置初始化大小、最小、最大 -->
- <property name="initialSize" value="1" />
- <property name="minIdle" value="1" />
- <property name="maxActive" value="20" />
- <!-- 配置获取连接等待超时的时间 -->
- <property name="maxWait" value="60000" />
- <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
- <property name="timeBetweenEvictionRunsMillis" value="60000" />
- <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
- <property name="minEvictableIdleTimeMillis" value="300000" />
- <property name="validationQuery" value="SELECT 'x'" />
- <property name="testWhileIdle" value="true" />
- <property name="testOnBorrow" value="false" />
- <property name="testOnReturn" value="false" />
- <!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
- <property name="poolPreparedStatements" value="false" />
- <property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
- <!-- 配置监控统计拦截的filters -->
- <property name="filters" value="stat" />
- </bean>
- <!-- mybatis文件配置,扫描所有mapper文件 -->
- <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource" p:configLocation="classpath:mybatis-config.xml" p:mapperLocations="classpath:com/eduoinfo/finances/bank/web/dao/*.xml" />
- <!-- spring与mybatis整合配置,扫描所有dao -->
- <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.eduoinfo.finances.bank.web.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory" />
- <!-- 对dataSource 数据源进行事务管理 -->
- <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource" />
- <!-- 配置使Spring采用CGLIB代理 -->
- <aop:aspectj-autoproxy proxy-target-class="true" />
- <!-- 启用对事务注解的支持 -->
- <tx:annotation-driven transaction-manager="transactionManager" />
- <!-- Cache配置 -->
- <cache:annotation-driven cache-manager="cacheManager" />
- <bean id="ehCacheManagerFactory" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean" p:configLocation="classpath:ehcache.xml" />
- <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager" p:cacheManager-ref="ehCacheManagerFactory" />
- </beans>
在类上 ,使用以下注解,实现bean 的声明
@Component 泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Service 用于标注业务层组件
@Controller 用于标注控制层组件(如srping mvc的controller,struts中的action)
@Repository 用于标注数据访问组件,即DAO组件
示例:
@Controller
@RequestMapping(value = "/test")
public class TestController {
}
------------------------------------------------------------------------------------------------------------------
在类的成员变量上,使用以下注解,实现属性的自动装配
@Autowired : 按类 的 类型进行装配
@Resource (推荐) : 1 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
2. 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
3.如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
4.如果既没有指定name,又没有指定type,则自动按照byName方式进行装配;如果没有匹配,则回退为一个原始类型进行匹配,如果匹配则自动装配;
@Resource注解在字段上,这样就不用写setter方法了,并且这个注解是属于J2EE的,减少了与spring的耦合。
示例:
@Resource
private TestServiceImpl testServiceImpl;