当我最开始接触Spring和hibernate开发的时候,也是从别人(学长)那里拷贝过来一个项目,自己学习研究,在当时,像applicationContext.xml这种配置文件也是他写成什么样,我就跟着照猫画虎的改,甚是觉得别扭,程序是万能的,为何我们不能突破常规,选择一种提高我们开发效率的方式?
说时迟,那时快,我决定全部采用注解来配置我的web应用,当时也不知道是否可行,不过,经过我的实践,最后成功了,在这里与大家分享。
首先看一下我的Spring 配置文件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:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/context/mvc" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/context/mvc http://www.springframework.org/schema/context/mvc/spring-mvc-3.0.xsd">
<aop:aspectj-autoproxy/>
<!-- 配置数据源 -->
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="location" value="/WEB-INF/datasource-conf.properties"></property>
</bean>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${driverClass}" />
<property name="jdbcUrl" value="${jdbcUrl}" />
<property name="user" value="${user}" />
<property name="password" value="${password}" />
<property name="initialPoolSize" value="${initialPoolSize}"></property>
<property name="minPoolSize" value="${minPoolSize}"></property>
<property name="maxPoolSize" value="${maxPoolSize}"></property>
<property name="maxIdleTime" value="${maxIdleTime}"></property>
<property name="acquireIncrement" value="${acquireIncrement}"></property>
<property name="idleConnectionTestPeriod" value="${idleConnectionTestPeriod}"></property>
<property name="acquireRetryAttempts" value="${acquireRetryAttempts}"></property>
<property name="breakAfterAcquireFailure" value="${breakAfterAcquireFailure}"></property>
<property name="maxStatements" value="${maxStatements}"></property>
<property name="testConnectionOnCheckout" value="${testConnectionOnCheckout}"></property>
</bean>
<!-- 启动注解自动装配 -->
<bean
class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
<!-- 启动基于注解(annotation)驱动 MVC-->
<context:component-scan base-package="net.woaoo">
<context:include-filter type="annotation"
expression="org.springframework.stereotype.Controller" />
</context:component-scan>
<!--基于注解映射的hibernateTemplate -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<bean class="net.woaoo.common.config.EntityBeanFinderFactoryBean">
<property name="classNamePattern" value="net.woaoo.**.model.**"/>
</bean>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
</props>
</property>
</bean>
<!-- HibernateTemplate -->
<bean id="hibernateTemplate" class="org.springframework.orm.hibernate3.HibernateTemplate">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- JDBCTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
我的修改主要有两点:
1.首先,bean不需要再配置文件中配置,在类中使用@Repository @Service 注解,spring会基于你的类名生成 首字母小写与之对应的对象,例如
@Service
public class ExampleService implements IExample{
}
你可以这样调用:
@Autowired
IExampleexampleService;
........
2.hibernate与数据库的映射类不通过手动配置,而是通过扫描的方式,这在一个新的项目的开发阶段很有帮助,能大大提高效率,数据库即便改来改去也不用修改配置文件,
传统的数据源dataSource 配置方式:
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<list>
<value>xxx.xxx.xxxModel</value>
<value>.........</value>
</list>
</property>
....
我的配置方式
<property name="dataSource" ref="dataSource" />
<property name="annotatedClasses">
<bean class="net.woaoo.common.config.EntityBeanFinderFactoryBean">
<property name="classNamePattern" value="net.woaoo.**.model.**"/>
</bean>
</property>
........
这个方法是我在逛spring论坛上看到的, springsource.org
分享下这个类:
package net.woaoo.common.config;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ResourceLoaderAware;
import org.springframework.core.io.Resource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternUtils;
/**
* This class finds all @Entity annotated classes defined by an ANT style class name pattern. Default
* pattern is **.domain.**
*
* @author marcus.bristav@dreampark.com
*/
public class EntityBeanFinderFactoryBean implements ResourceLoaderAware,
FactoryBean {
private ResourcePatternResolver resolver;
private List<Class> managedClasses = null;
private String classPattern = "classpath*:**/domain/**/*.class";
static final int UTF = 1, INTEGER = 3, FLOAT = 4, LONG = 5, DOUBLE = 6,
CLASS = 7, STRING = 8, FIELD_REF = 9, METHOD_REF = 10,
INTERFACE_METHOD_REF = 11, NAME_AND_TYPE = 12;
public void setResourceLoader(ResourceLoader resourceLoader) {
resolver = ResourcePatternUtils
.getResourcePatternResolver(resourceLoader);
}
/**
* Determines what class files to scan for @Entity annotations. The string
* behaves like ANT paths. Default value is "**.domain.**"
* @param packagePattern
*/
public void setClassNamePattern(String packagePattern) {
classPattern = "classpath*:" + packagePattern.replace(".", "/")
+ "/*.class";
}
public Object getObject() throws Exception {
if (managedClasses == null) {
loadManagedClasses();
}
return managedClasses;
}
public Class getObjectType() {
return List.class;
}
public boolean isSingleton() {
return true;
}
private void loadManagedClasses() throws Exception {
managedClasses = new ArrayList<Class>();
Resource[] resources = resolver.getResources(classPattern);
if (resources != null) {
for (Resource res : resources) {
Class klass = getClass(res);
if (hasEntityAnnotation(klass)) {
managedClasses.add(klass);
}
}
}
}
private Class getClass(Resource res) throws Exception{
String className = className(res);
System.out.println(className);
return Class.forName(className);
}
private boolean hasEntityAnnotation(Class klass) {
return (klass.getAnnotation(javax.persistence.Entity.class) != null);
}
// Parses java class files (byte code) to find class name
// Must be a better way to do this...
private String className(Resource res) throws Exception {
InputStream is = res.getInputStream();
Map<Integer, Integer> offsetTable = new HashMap<Integer, Integer>();
Map<Integer, String> classNameTable = new HashMap<Integer, String>();
DataInputStream data = new DataInputStream(new BufferedInputStream(is));
int magic = data.readInt();
int minorVersion = data.readShort();
int majorVersion = data.readShort();
int constant_pool_count = data.readShort();
int[] constant_pool = new int[constant_pool_count];
for (int i = 1; i < constant_pool_count; i++) {
int tag = data.read();
int tableSize;
switch (tag) {
case CLASS:
int offset = data.readShort();
offsetTable.put(i, offset);
break;
case UTF:
int length = data.readShort();
char[] bytes = new char[length];
for (int k = 0; k < bytes.length; k++)
bytes[k] = (char) data.read();
String className = new String(bytes);
classNameTable.put(i, className);
break;
case LONG:
case DOUBLE:
data.readLong();
i++;
break;
case STRING:
data.readShort();
break;
default:
data.readInt();
}
}
short access_flags = data.readShort();
int this_class = data.readShort();
int super_class = data.readShort();
String thisClassName = classNameTable.get(offsetTable.get(this_class));
is.close();
return thisClassName.replace("/", ".");
}
}