Spring配置:集成Hibernate、JacksonJSON、AspectJ等框架
本文提及的该套配置文件,覆盖了JavaEE项目开发的最常见需求,包括:依赖注入、事务控制、AOP、任务调度、缓存、MVC框架等方面的内容。
容易改变的配置项独立到属性文件中:
Spring配置文件部分:
Spring MVC配置文件部分:
ehcache配置部分:
Web.xml配置(使用了Spring的JavaConfig):
Java Config类:
Maven依赖包列表:
Maven插件配置(支持AspectJ):
容易改变的配置项独立到属性文件中:
1 2 3 4 5 6 |
hibernateDialect=org.hibernate.dialect.MySQL5Dialect #启用了log4jdbc支持 jdbcDriver=net.sf.log4jdbc.DriverSpy jdbcDriverUrl=jdbc:log4jdbc:mysql://192.168.0.201:3306/initpemsdb1.1.1 jdbcUserName=root jdbcPassword=root |
Spring配置文件部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 |
<?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:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:task="http://www.springframework.org/schema/task" xmlns:cache="http://www.springframework.org/schema/cache" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-3.0.xsd http://www.springframework.org/schema/cache http://www.springframework.org/schema/cache/spring-cache-3.1.xsd "> <!-- 定义属性,在后面的配置中可以使用#{appCfg.xxx}引用 --> <util:properties id="appCfg" location="classpath:applicationConfig.properties" /> <!-- 包扫描配置 --> <context:component-scan base-package="cc.gmem.demo"> <!-- 去除Java Config类 --> <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration" /> <!-- 去除Spring MVC类 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> <!-- 匹配AspectJ Pattern的类被去除 --> <context:exclude-filter type="aspectj" expression="cc.gmem.demo.aop.web.*" /> </context:component-scan> <!-- 启用注解支持 --> <context:annotation-config /> <!-- 支持@Configurable注解 --> <context:spring-configured /> <!-- 启用注解方式的事务:基于AspectJ织入 --> <tx:annotation-driven transaction-manager="txManager" mode="aspectj" /> <!-- 启用注解方式的缓存配置:基于AspectJ织入 --> <cache:annotation-driven cache-manager="cacheManager" mode="aspectj" /> <!-- 启用注解方式的任务执行(例如@Async):基于AspectJ织入 --> <task:annotation-driven executor="taskExecutor" mode="aspectj" /> <!-- 任务调度器配置,pool-size为线程池大小,限制了同时最多被调度的任务 --> <task:scheduler pool-size="100" id="scheduler" /> <!-- 任务计划列表,支持固定频率、固定延迟、Cron表达式等 --> <task:scheduled-tasks scheduler="scheduler"> <task:scheduled fixed-rate="120000" method="run" ref="hibernateStatisticsMonitor" /> </task:scheduled-tasks> <!-- 任务执行器,用于异步执行任务 --> <task:executor id="taskExecutor" keep-alive="3600" pool-size="10-100" queue-capacity="10000" rejection-policy="CALLER_RUNS" /> <!-- 引入其它Spring配置文件 --> <import resource="report-and-etl.xml" /> <!-- Hibernate配置 --> <bean id="dataSource" class="org.logicalcobwebs.proxool.ProxoolDataSource"> <property name="alias" value="connectionPool" /> <property name="driver" value="#{appCfg.jdbcDriver}" /> <property name="driverUrl" value="#{appCfg.jdbcDriverUrl}" /> <property name="user" value="#{appCfg.jdbcUserName}" /> <property name="password" value="#{appCfg.jdbcPassword}" /> <property name="statistics" value="10s" /> <property name="minimumConnectionCount" value="10" /> <property name="maximumConnectionCount" value="100" /> <property name="simultaneousBuildThrottle" value="10" /> <property name="maximumActiveTime" value="3600000" /> </bean> <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate" autowire="byName" /> <bean id="nativeJdbcExtractor" class="org.springframework.jdbc.support.nativejdbc.CommonsDbcpNativeJdbcExtractor" lazy-init="true" /> <bean id="sessionFactory" p:dataSource-ref="dataSource" class="cc.gmem.demo.hibernate.AnnotationSessionFactoryBean" depends-on="appCfg" > <property name="packagesToScan"> <list> <value>cc.gmem.demo.**.domain</value> </list> </property> <property name="hibernateProperties"> <value> hibernate.dialect=#{appCfg.hibernateDialect} hibernate.jdbc.batch_size=30 hibernate.show_sql=false hibernate.format_sql=true hibernate.generate_statistics=true hibernate.transaction.factory_class=org.hibernate.transaction.JDBCTransactionFactory hibernate.current_session_context_class=org.springframework.orm.hibernate3.SpringSessionContext hibernate.query.factory_class=org.hibernate.hql.ast.ASTQueryTranslatorFactory hibernate.hbm2ddl.auto=update #启用二级缓存 hibernate.cache.use_second_level_cache=true hibernate.cache.use_query_cache=true hibernate.cache.region.factory_class=org.hibernate.cache.SingletonEhCacheRegionFactory </value> </property> </bean> <!-- Spring缓存配置 --> <bean id="cacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager"> <property name="cacheManager" ref="ehcache" /> </bean> <bean id="ehcache" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean"> <property name="configLocation"> <value>classpath:ehcache.xml</value> </property> <property name="shared" value="true" /> </bean> <bean id="hibernateStatisticsMonitor" class="cc.gmem.demo.hibernate.HibernateStatisticsMonitor" /> <bean id="txManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager" p:sessionFactory-ref="sessionFactory" /> <!-- Velocity引擎配置 --> <bean id="velocityEngine" class="org.apache.velocity.app.VelocityEngine"> <constructor-arg type="java.util.Properties"> <value> <![CDATA[ #{T(org.apache.velocity.runtime.RuntimeConstants).RUNTIME_LOG_LOGSYSTEM_CLASS}=org.apache.velocity.runtime.log.Log4JLogChute runtime.log.logsystem.log4j.logger=velocityLogger #{T(org.apache.velocity.runtime.RuntimeConstants).INPUT_ENCODING}=UTF-8 #{T(org.apache.velocity.runtime.RuntimeConstants).OUTPUT_ENCODING}=UTF-8 #{T(org.apache.velocity.runtime.RuntimeConstants).VM_PERM_ALLOW_INLINE}=true #{T(org.apache.velocity.runtime.RuntimeConstants).RESOURCE_LOADER}=class #{T(org.apache.velocity.runtime.RuntimeConstants).PARSER_POOL_SIZE}=100 class.resource.loader.class=org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader ]]> </value> </constructor-arg> </bean> <!--国际化支持--> <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> <property name="basenames"> <list> <value>classpath:message.gmemdemo</value> </list> </property> <property name="defaultEncoding" value="UTF-8" /> <property name="cacheSeconds" value="5" /> </bean> <!--Jackson JSON --> <bean id="objectMapper" class="com.fasterxml.jackson.databind.ObjectMapper" autowire="byType" /> <!-- Spring类型转换服务,特别是用于时间日期格式转换 --> <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"> <property name="converters"> <set> <bean class="net.greenmemory.spring.converter.DateTimeConvertor"> <constructor-arg> <array> <value>yyyy-MM-dd</value> <value>yyyy-MM-dd HH:mm:ss</value> <value>yyyy-MM-dd HH:mm:ss.SSS</value> </array> </constructor-arg> </bean> </set> </property> <property name="formatters"> <set> <bean class="org.springframework.format.datetime.DateFormatter"> <constructor-arg> <value>yyyy-MM-dd</value> </constructor-arg> </bean> </set> </property> <property name="formatterRegistrars"> <set> </set> </property> </bean> </beans> |
Spring MVC配置文件部分:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation=" http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.1.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd "> <context:component-scan base-package="cc.gmem.demo.**.ctrl"> <context:exclude-filter type="annotation" expression="org.springframework.context.annotation.Configuration" /> </context:component-scan> <context:component-scan base-package="cc.gmem.demo.aop.web" /> <context:annotation-config /> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.json.jacksonjson.MappingJackson2HttpMessageConverter"> <property name="objectMapper" ref="objectMapper" /> </bean> </mvc:message-converters> </mvc:annotation-driven> <mvc:interceptors> <bean id="openSessionInViewInterceptor" class="org.springframework.orm.hibernate3.support.OpenSessionInViewInterceptor"> <property name="sessionFactory" ref="sessionFactory" /> </bean> <mvc:interceptor> <mvc:mapping path="/home/*" /> <!-- 自定义MVC拦截器 --> <bean class="cc.gmem.demo.spring.LogonInterceptor" /> </mvc:interceptor> </mvc:interceptors> <bean id="viewResolver" class="org.springframework.web.servlet.view.UrlBasedViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" /> <property name="prefix" value="/WEB-INF/jsp/" /> <property name="suffix" value=".jsp" /> <property name="order" value="0" /> </bean> <mvc:resources mapping="/css/**" location="/css/" /> <mvc:resources mapping="/icons/**" location="/icons/" /> <mvc:resources mapping="/images/**" location="/images/" /> <mvc:resources mapping="/themes/**" location="/themes/" /> <mvc:resources mapping="/js/**" location="/js/" /> </beans> |
ehcache配置部分:
1 2 3 4 5 6 7 |
<?xml version="1.0" encoding="UTF-8"?> <ehcache> <diskStore path="D:/Temp/ehcache" /> <defaultCache eternal="false" /> <cache name="entityCache" eternal="false" maxElementsInMemory="1000" timeToIdleSeconds="120" timeToLiveSeconds="3600" overflowToDisk="true" memoryStoreEvictionPolicy="LFU" /> </ehcache> |
Web.xml配置(使用了Spring的JavaConfig):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 |
<?xml version="1.0" encoding="UTF-8"?> <web-app 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"> <context-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </context-param> <context-param> <param-name>contextConfigLocation</param-name> <param-value>cc.gmem.demo.spring.SpringBeanDefinitionRegistrar</param-value> </context-param> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextClass</param-name> <param-value>org.springframework.web.context.support.AnnotationConfigWebApplicationContext</param-value> </init-param> <init-param> <param-name>contextConfigLocation</param-name> <param-value>cc.gmem.demo.spring.SpringMVCBeanDefinitionRegistrar</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>adminServlet</servlet-name> <url-pattern>/proxool</url-pattern> </servlet-mapping> <session-config> <session-timeout>60</session-timeout> </session-config> <error-page> <error-code>404</error-code> <location>/WEB-INF/jsp/error-404.jsp</location> </error-page> <error-page> <error-code>401</error-code> <location>/WEB-INF/jsp/error-401.jsp</location> </error-page> <error-page> <error-code>500</error-code> <location>/WEB-INF/jsp/error-500.jsp</location> </error-page> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> </web-app> |
Java Config类:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Configuration /* XML-based bean definitions */ @ImportResource ( "classpath:applicationContext.xml" ) public class SpringBeanDefinitionRegistrar { /* Auto injected spring context */ @SuppressWarnings ( "unused" ) @Inject private ApplicationContext applicationContext; /* Programmatic bean definition */ @Bean ( name = "helper" ) public Helper helper() { Helper helper = new Helper(); return helper; } } |
1 2 3 4 5 6 |
@Configuration @ImportResource ( "classpath:spring-mvc.xml" ) public class SpringMVCBeanDefinitionRegistrar { } |
Maven依赖包列表:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 |
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>3.1.2.RELEASE</spring.version> <hibernate.version>3.6.10.Mod</hibernate.version> <aspectj.version>1.6.11</aspectj.version> <jackson.version>2.0.4</jackson.version> </properties> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>${hibernate.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>${aspectj.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>${jackson.version}</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.4</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.el</groupId> <artifactId>el-api</artifactId> <version>2.2</version> <scope>provided</scope> </dependency> <dependency> <groupId>proxool</groupId> <artifactId>proxool</artifactId> <version>0.9.1</version> </dependency> <dependency> <groupId>org.javassist</groupId> <artifactId>javassist</artifactId> <version>3.15.0-GA</version> </dependency> <dependency> <groupId>net.sf.log4jdbc</groupId> <artifactId>log4jdbc3</artifactId> <version>1.2-ext-3</version> </dependency> <dependency> <groupId>com.sqlinform</groupId> <artifactId>sqlinform</artifactId> <version>0.0.1</version> </dependency> <dependency> <groupId>javax.annotation</groupId> <artifactId>jsr250-api</artifactId> <version>1.0</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <dependency> <groupId>joda-time</groupId> <artifactId>joda-time</artifactId> <version>2.1</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.2.2</version> </dependency> <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>opensymphony</groupId> <artifactId>quartz-all</artifactId> <version>1.6.3</version> </dependency> </dependencies> |
Maven插件配置(支持AspectJ):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
<plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>aspectj-maven-plugin</artifactId> <version>1.4</version> <executions> <execution> <id>compile</id> <configuration> <XnoInline>true</XnoInline> <forceAjcCompile>true</forceAjcCompile> <showWeaveInfo>true</showWeaveInfo> <source>1.5</source> <target>1.5</target> <encoding>UTF-8</encoding> <verbose>true</verbose> <outxml>true</outxml> <aspectLibraries> <aspectLibrary> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> </aspectLibrary> </aspectLibraries> </configuration> <goals> <goal>compile</goal> </goals> </execution> </executions> </plugin> |
Leave a Reply