Spring配置:启用Jetty SSL传输的CXF
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 |
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:sec="http://cxf.apache.org/configuration/security" xmlns:http="http://cxf.apache.org/transports/http/configuration" xmlns:httpj="http://cxf.apache.org/transports/http-jetty/configuration" xmlns:cxf="http://cxf.apache.org/core" xmlns:jaxws="http://cxf.apache.org/jaxws" xsi:schemaLocation=" http://cxf.apache.org/configuration/security http://cxf.apache.org/schemas/configuration/security.xsd http://cxf.apache.org/transports/http/configuration http://cxf.apache.org/schemas/configuration/http-conf.xsd http://cxf.apache.org/transports/http-jetty/configuration http://cxf.apache.org/schemas/configuration/http-jetty.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://cxf.apache.org/core http://cxf.apache.org/schemas/core.xsd http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd "> <import resource="classpath:META-INF/cxf/cxf.xml" /> <import resource="classpath:META-INF/cxf/cxf-extension-jaxws.xml" /> <cxf:bus> <cxf:features> <cxf:logging /> </cxf:features> </cxf:bus> <bean id="cfg" class="sparknet.canary.core.cfg" init-method="init"> <property name="params"> <value> <![CDATA[ http.port=5050 https.port=5051 https.keyManagers.keyStore.type=JKS https.keyManagers.keyPassword=sparknet https.keyManagers.keyStore.password=sparknet https.keyManagers.keyStore.url=#{@cfg.baseDirUrl}/work/security/key/platform.jks https.trustManagers.keyStore.type=JKS https.trustManagers.keyStore.password=sparknet https.trustManagers.keyStore.url=#{@cfg.baseDirUrl}/work/security/cert/trust.jks http.minThreads=5 http.maxThreads=50 ]]> </value> </property> </bean> <bean name="dataTransServiceImplHttp" class="cc.gmem.demo.ws.DataTransServiceImpl" autowire="byName"> <property name="https" value="false" /> </bean> <bean name="dataTransServiceImplHttps" class="cc.gmem.demo.ws.DataTransServiceImpl" autowire="byName"> <property name="https" value="true" /> </bean> <jaxws:endpoint id="dataTransServiceHttp" implementor="#dataTransServiceImplHttp" address="http://0.0.0.0:#{@cfg.params['http.port']}/dataTransService" publish="true" /> <jaxws:endpoint id="dataTransServiceHttps" implementor="#dataTransServiceImplHttps" address="https://0.0.0.0:#{@cfg.params['https.port']}/dataTransService" publish="true" /> <httpj:engine-factory bus="cxf"> <httpj:identifiedThreadingParameters id="threadPool"> <httpj:threadingParameters minThreads="#{@cfg.params['http.minThreads']}" maxThreads="#{@cfg.params['http.maxThreads']}" /> </httpj:identifiedThreadingParameters> <httpj:engine port="#{@cfg.params['http.port']}"> <httpj:threadingParametersRef id="threadPool" /> <httpj:connector> <bean class="org.eclipse.jetty.server.bio.SocketConnector"> <property name="port" value="#{@cfg.params['http.port']}" /> </bean> </httpj:connector> </httpj:engine> <httpj:engine port="#{@cfg.params['https.port']}"> <httpj:tlsServerParameters> <sec:keyManagers keyPassword="#{@cfg.params['https.keyManagers.keyPassword']}"> <sec:keyStore type="#{@cfg.params['https.keyManagers.keyStore.type']}" url="#{@cfg.params['https.keyManagers.keyStore.url']}" password="#{@cfg.params['https.keyManagers.keyStore.password']}" /> </sec:keyManagers> <sec:trustManagers> <sec:keyStore type="#{@cfg.params['https.trustManagers.keyStore.type']}" url="#{@cfg.params['https.trustManagers.keyStore.url']}" password="#{@cfg.params['https.trustManagers.keyStore.password']}" /> </sec:trustManagers> <sec:cipherSuitesFilter> <sec:include>.*_EXPORT_.*</sec:include> <sec:include>.*_EXPORT1024_.*</sec:include> <sec:include>.*_WITH_DES_.*</sec:include> <sec:include>.*_WITH_AES_.*</sec:include> <sec:include>.*_WITH_NULL_.*</sec:include> <sec:exclude>.*_DH_anon_.*</sec:exclude> </sec:cipherSuitesFilter> <sec:clientAuthentication want="true" required="true" /> </httpj:tlsServerParameters> <httpj:threadingParametersRef id="threadPool" /> <httpj:connector> <bean class="org.eclipse.jetty.server.ssl.SslSocketConnector"> <property name="port" value="#{@cfg.params['https.port']}" /> <property name="password" value="#{@cfg.params['https.keyManagers.keyStore.password']}" /> <property name="trustPassword" value="#{@cfg.params['https.trustManagers.keyStore.password']}" /> <property name="keyPassword" value="#{@cfg.params['https.keyManagers.keyPassword']}" /> <property name="protocol" value="TLS" /> <property name="keystore" value="#{@cfg.params['https.keyManagers.keyStore.url']}" /> <property name="keystoreType" value="#{@cfg.params['https.keyManagers.keyStore.type']}" /> <property name="truststore" value="#{@cfg.params['https.trustManagers.keyStore.url']}" /> <property name="truststoreType" value="#{@cfg.params['https.trustManagers.keyStore.type']}" /> <property name="wantClientAuth" value="false" /> <property name="needClientAuth" value="false" /> </bean> </httpj:connector> </httpj:engine> </httpj:engine-factory> </beans> |
使用JDK的keytool密钥对
使用JDK自带的keytool命令可以生成JKS(Java KeyStore)文件,作为数字证书库使用。在配置SSL时,一般需要用到两个JKS:信任库、证书库(对应上节配置文件中的truststore、keystore)。
下面是生成证书库的示例:
1 |
keytool -genkey -alias platform -keyalg RSA -keypass key_password -storepass store_password -dname "CN=DataTrans Platform, OU=, O=Gmem.cc, L=Nan Jing, ST=Jiang Su, C=CN" -validity 3650 -keystore platform.jks |
12 years ago
0
JacksonJson知识集锦
基础知识
Jackson JSON 提供了一系列API,便于Java程序读写JSON字符串。它具有强大对数据绑定能力,可以方便的在Java对象和JSON字符串之间进行转换。
创建JSON
从Java对象创建(绑定)
代码示例:
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 |
ObjectMapper mapper = new ObjectMapper(); // 启用缩进,更易读 mapper.configure(SerializationFeature.INDENT_OUTPUT, true); // 输出Map类型时,以键排序 mapper.configure(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS, true); // 日期对象的默认输出格式 mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd")); /** * Java字段名/属性名到JSON字段的映射策略 */ mapper.setPropertyNamingStrategy( new PropertyNamingStrategy() { public String nameForField( MapperConfig config, AnnotatedField field, String defaultName ) { if ( field.getFullName().equals( "cc.gmem.vo.Entity#name" ) ) return "Entity-Name"; return super.nameForField( config, field, defaultName ); } public String nameForGetterMethod( MapperConfig config, AnnotatedMethod method, String defaultName ) { if ( method.getAnnotated().getDeclaringClass().equals( Entity.class ) && defaultName.equals( "no" ) ) return "Entity-No"; return super.nameForGetterMethod( config, method, defaultName ); } } ); // 忽略空属性/字段 mapper.setSerializationInclusion(Include.NON_EMPTY); // 把entity转换为JSON然后写入标准输出 mapper.writeValue(System.out, entity); |
从JsonNode树创建
示例代码:
1 2 3 4 5 6 7 8 9 10 11 |
// 此工厂用于创建JsonNode对象 JsonNodeFactory factory = new JsonNodeFactory( false ); // 此工厂用于创建JSON的生成器、解析器 JsonFactory jsonFactory = new JsonFactory(); // 写入到标准输出 JsonGenerator generator = jsonFactory.createGenerator( System.out ); ObjectMapper mapper = new ObjectMapper(); // 根节点 ObjectNode entity = factory.objectNode(); entity.put( "name", "entityname" ); mapper.writeTree( generator, entity ); |
构建JSON流
这种方式很不直观,但是节约内存:
解析JSON
解析JSON流
Jackson提供了一种底层API,允许逐符号的处理JSON…
阅读全文
12 years ago
0
Ubuntu下安装JDK1.7
从Oracle官网下载软件:
解压,并移动到习惯的存放位置:
设置环境变量:
阅读全文
1 |
wget --no-cookies --no-check-certificate --header "Cookie: gpw_e24=http%3A%2F%2Fwww.oracle.com%2F; oraclelicense=accept-securebackup-cookie" "http://download.oracle.com/otn-pub/java/jdk/7u67-b01/jdk-7u67-linux-x64.tar.gz" |
1 2 3 4 5 |
#解压安装文件 tar -zxvf jdk-7u67-linux-x64.tar.gz rm jdk-7u67-linux-x64.tar.gz #移动解压文件 mv jdk1.7.0_67 /usr/local/jdk/1.7 |
12 years ago
0
使用Atomikos来进行分布式事务(XA)开发
结合Spring使用
和Spring集成的时候,不需要JNDI服务器
注意,不支持Spring的事务传播性:PROPAGATION_NESTED
JTA事务管理器配置样例:
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 |
<bean id="localLogAdministrator" class="com.atomikos.icatch.admin.imp.LocalLogAdministrator" /> <bean id="userTransactionService" class="com.atomikos.icatch.config.UserTransactionServiceImp" init-method="init" destroy-method="shutdownForce"> <constructor-arg> <!-- 配置Atomikos属性 --> <props> <prop key="com.atomikos.icatch.service">com.atomikos.icatch.standalone.UserTransactionServiceFactory</prop> </props> </constructor-arg> <property name="initialLogAdministrators"> <list> <ref bean="localLogAdministrator" /> </list> </property> </bean> <!-- Atomikos 事务管理器配置 --> <bean id="atomikosTransactionManager" class="com.atomikos.icatch.jta.UserTransactionManager" init-method="init" destroy-method="close" depends-on="userTransactionService"> <property name="startupTransactionService" value="false" /> <!-- close()时是否强制终止事务 --> <property name="forceShutdown" value="false" /> </bean> <!-- Atomikos UserTransaction配置 --> <bean id="atomikosUserTransaction" class="com.atomikos.icatch.jta.UserTransactionImp" depends-on="userTransactionService"> <property name="transactionTimeout" value="300" /> </bean> <!-- JTA事务管理器 --> <bean id="jtaTransactionManager" class="org.springframework.transaction.jta.JtaTransactionManager" depends-on="userTransactionService"> <property name="transactionManager" ref="atomikosTransactionManager" /> <property name="userTransaction" ref="atomikosUserTransaction" /> </bean> |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
<bean id="xaFactory" class="org.apache.activemq.ActiveMQXAConnectionFactory"> <property name="brokerURL" value="tcp://localhost:61616" /> </bean> <bean id="jmsFactory" class="com.atomikos.jms.AtomikosConnectionFactoryBean" init-method="init" destroy-method="close"> <property name="uniqueResourceName" value="amq" /> <property name="xaConnectionFactory" ref="xaFactory" /> </bean> <bean id="tipsMessageListener" class="cc.gmem.demo.TipsMessageListener" /> <!-- 接收消息 --> <jms:listener-container container-type="default" connection-factory="jmsFactory" transaction-manager="jtaTransactionManager" session-transacted="true"> <jms:listener destination="TIPS.10000.BATCH" ref="tipsMessageListener" method="onMessage" /> </jms:listener-container> <!-- 发送消息 --> <bean id="jmsTemplate" class="org.springframework.jms.core.JmsTemplate"> <property name="connectionFactory"> <ref bean="jmsFactory" /> </property> <property name="receiveTimeout" value="1000" /> <property name="sessionTransacted" value="true" /> </bean> |
不使用Spring,单独和Hibernate集成
Hibe… 阅读全文
12 years ago
0
Spring配置:集成Hibernate、JacksonJSON、AspectJ等框架
本文提及的该套配置文件,覆盖了JavaEE项目开发的最常见需求,包括:依赖注入、事务控制、AOP、任务调度、缓存、MVC框架等方面的内容。
容易改变的配置项独立到属性文件中:
Spring配置文件部分:
Spring MVC配置文件部分:
ehcache配置部分:
Web.xml配置(使用了Spring的JavaConfig):
Java Config类:
Maven依赖包列表:
Mave…
阅读全文
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 |
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> |
12 years ago
0
基于JavaConfig方式的Spring+Hibernate集成
JavaConfig类
包含Spring、Hibernate、事务管理等功能的样例
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 |
package sparknet.wnet.saic.intf.spring; import java.io.IOException; import java.util.Properties; import javax.inject.Inject; import javax.sql.DataSource; import net.greenmemory.breeze.persist.OracleProxoolDataSource; import net.greenmemory.commons.db.QueryRunner; import net.greenmemory.commons.lang.NumberUtils; import net.greenmemory.spring.core.io.ClassPathResource; import org.hibernate.SessionFactory; import org.springframework.aop.framework.autoproxy.InfrastructureAdvisorAutoProxyCreator; import org.springframework.beans.factory.BeanInitializationException; import org.springframework.context.ApplicationContext; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.ComponentScan.Filter; import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.EnableAspectJAutoProxy; import org.springframework.context.annotation.FilterType; import org.springframework.jdbc.core.JdbcTemplate; import org.springframework.orm.hibernate3.HibernateTransactionManager; import org.springframework.transaction.PlatformTransactionManager; import org.springframework.transaction.annotation.AnnotationTransactionAttributeSource; import org.springframework.transaction.interceptor.TransactionAttributeSourceAdvisor; import org.springframework.transaction.interceptor.TransactionInterceptor; import cc.gmem.tools.hibernatetools.spring.Hibernate3LocalSessionFactoryBean; @Configuration @ComponentScan ( basePackages = { "cc.gmem.saic", "cc.gmem.intf" }, excludeFilters = { @Filter ( type = FilterType.ANNOTATION, value = Configuration.class ) } ) @EnableAspectJAutoProxy public class BeanDefinitionRegistrar { @Inject private ApplicationContext applicationContext; @Bean ( name = "cfg" ) public Properties getAppConfig() { Properties props = new Properties(); try { props.load( new ClassPathResource( "wsi.properties" ).getInputStream() ); } catch ( IOException e ) { throw new BeanInitializationException( e.getMessage(), e ); } return props; } @Bean ( name = "dataSource" ) public DataSource getDataSource() { OracleProxoolDataSource dataSource = new OracleProxoolDataSource(); dataSource.setAlias( getAppConfig().getProperty( "jdbc.alias" ) ); dataSource.setDriver( getAppConfig().getProperty( "jdbc.driverClass" ) ); dataSource.setDriverUrl( getAppConfig().getProperty( "jdbc.url" ) ); dataSource.setUser( getAppConfig().getProperty( "jdbc.user" ) ); dataSource.setPassword( getAppConfig().getProperty( "jdbc.password" ) ); dataSource.setMinimumConnectionCount( NumberUtils.toInt( getAppConfig().getProperty( "jdbc.minimumConnectionCount" ), 10 ) ); dataSource.setMaximumConnectionCount( NumberUtils.toInt( getAppConfig().getProperty( "jdbc.maximumConnectionCount" ), 100 ) ); dataSource.setSimultaneousBuildThrottle( NumberUtils.toInt( getAppConfig().getProperty( "jdbc.simultaneousBuildThrottle" ), 50 ) ); dataSource.setMaximumActiveTime( NumberUtils.toInt( getAppConfig().getProperty( "jdbc.maximumActiveTime" ), 1200000 ) ); dataSource.setEncrypted( false ); dataSource.init(); return dataSource; } @Bean ( name = "sessionFactory" ) public SessionFactory getSessionFactory() throws Exception { Hibernate3LocalSessionFactoryBean bean = new Hibernate3LocalSessionFactoryBean(); bean.setApplicationContext( applicationContext ); bean.setDataSource( getDataSource() ); bean.setMappingResources( new String[] { "wnetJhInterface.hbm.xml" } ); bean.setAutoRegister( true ); Properties hibernateProperties = new Properties(); hibernateProperties.setProperty( "hibernate.dialect", "org.hibernate.dialect.Oracle10gDialect" ); hibernateProperties.setProperty( "hibernate.jdbc.batch_size", "100" ); hibernateProperties.setProperty( "hibernate.default_entity_mode", "dom4j" ); hibernateProperties.setProperty( "hibernate.transaction.factory_class", "org.hibernate.transaction.JDBCTransactionFactory" ); hibernateProperties.setProperty( "hibernate.current_session_context_class", "org.springframework.orm.hibernate3.SpringSessionContext" ); bean.setHibernateProperties( hibernateProperties ); bean.afterPropertiesSet(); return bean.getObject(); } @Bean ( name = "txManager" ) public PlatformTransactionManager getTransactionManager() throws Exception { HibernateTransactionManager txMgr = new HibernateTransactionManager(); txMgr.setSessionFactory( getSessionFactory() ); return txMgr; } @Bean ( name = "jdbcTemplate" ) public JdbcTemplate getJdbcTemplate() { return new JdbcTemplate( getDataSource() ); } @Bean ( name = "queryRunner" ) public QueryRunner getQueryRunner() { return new QueryRunner( getDataSource() ); } @Bean public AnnotationTransactionAttributeSource transactionAttributeSource() { return new AnnotationTransactionAttributeSource(); } @Bean public TransactionInterceptor transactionInterceptor() throws Exception { return new TransactionInterceptor( getTransactionManager(), transactionAttributeSource() ); } @Bean public TransactionAttributeSourceAdvisor internalTransactionAdvisor() throws Exception { return new TransactionAttributeSourceAdvisor( transactionInterceptor() ); } @Bean public InfrastructureAdvisorAutoProxyCreator internalAutoProxyCreator() { return new InfrastructureAdvisorAutoProxyCreator(); } } |
初始化Spring ApplicationContext的代码
1 2 |
ApplicationContext ctx = new AnnotationConfigApplicationContext(BeanDefinitionRegistrar.class); DataSource ds= ctx.getBean(DataSource.class); |
12 years ago
0
SpringMVC知识集锦
基于仿冒的SpringMVC测试用例示意
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 |
package cc.gmem.demo.ctrl; import static org.junit.Assert.*; import javax.inject.Inject; import net.greenmemory.commons.lang.StringUtils; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.LoggerFactory; import org.springframework.mock.web.MockHttpServletRequest; import org.springframework.mock.web.MockHttpServletResponse; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.transaction.TransactionConfiguration; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter; import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping; import com.fasterxml.jackson.databind.ObjectMapper; @RunWith ( SpringJUnit4ClassRunner.class ) @ContextConfiguration ( locations = { "/spring-classgen-disabled.xml", "/spring-mvc.xml" } ) @TransactionConfiguration ( transactionManager = "txManager", defaultRollback = true ) public class SpringMVCControllerTest { private static final org.slf4j.Logger LOGGER = LoggerFactory.getLogger( SpringMVCControllerTest.class ); @Inject private RequestMappingHandlerAdapter handlerAdapter; @Inject private RequestMappingHandlerMapping handlerMapping; @Inject private SessionFactory sf; @Inject private ObjectMapper om; private MockHttpServletRequest request; private MockHttpServletResponse response; @Before @Transactional public void setUp() { request = new MockHttpServletRequest(); response = new MockHttpServletResponse(); Session sess = sf.getCurrentSession(); } @Test @Transactional public void testController() throws Exception { request.setRequestURI( "/uri/" ); //设置请求的URI Object handler = handlerMapping.getHandler( request ).getHandler(); //获取Handler对象(就是控制器类) handlerAdapter.handle( request, response, handler ); //转发给Handler处理,并获取响应 String contentType = response.getContentType(); String json = response.getContentAsString(); assertTrue( StringUtils.containsIgnoreCase( contentType, "json" ) ); assertTrue( StringUtils.containsIgnoreCase( contentType, "utf-8" ) ); } } |
常用问题
强制产生JSON格式的结果
配置 @RequestMapping( produces = "application/json" )
SpringMVC 设置 /* 过滤全部,导致JSP无法显示的问题
找不到控制器类的问题:No mapping found for HTTP request with URI
- 注意URL拦截的前置部分,如/admin,不要再控制器的映射路径中体现,例如地址/admin/user在控制器中直接配: /user
使用…
12 years ago
0
Spring MVC 3.0学习笔记
Spring MVC框架简介
Spring MVC 3.0新特性
- 支持REST风格的URL
- 添加更多注解,可完全注解驱动
- 引入HTTP输入输出转换器(HttpMessageConverter)
- 和数据转换、格式化、验证框架无缝集成
- 对静态资源处理提供特殊支持 更加灵活…
12 years ago
0
Eclipse下进行基于AspectJ的AOP编程
简述
本文介绍在Eclipse下,结合Maven进行基于AspectJ的AOP编程(编译期织入)的基础知识,并给出简单的示例。 本文中使用的Eclipse版本为:3.7.1,AJDT版本为:1.6
环境准备
- 安装AspectJ Development Tools(AJDT)插件 可以到Eclipse Marketplace搜索“AJDT”,注意版本要和你的Eclipse版本匹配。或者从Update Site:http://download.eclipse.or…
12 years ago
0