Spring Boot学习笔记
简介
Spring Boot是Spring的一个子项目,它让创建独立运行(通过java -jar)的、产品级别的Spring应用变得简单:
- 支持创建独立运行于JVM中的Spring程序
- 内嵌Tomcat、Jetty或者Undertow,不需要部署War包
- 简化Ma…
7 years ago
0
1
Spring对WebSocket的支持
简介
Spring 4.x引入了新的模块spring-websocket,对WebSocket提供了全面的支持,Spring的WebSocket实现遵循JSR-356(Java WebSocket API),并且添加了一些额外特性。
绝大部分现代浏览器均支持WebSocket,包括…
阅读全文
7 years ago
0
1
Spring对JMS的支持
简介
Spring 提供了JMS的集成,简化JMS的使用,提供的API封装类似于Spring的JDBC集成。
JMS的功能大体上分为两类——接收、发送消息。Spring提供了:
- JmsTemplate来完成消息的发送、同步接收
- 消息监听器容器(message li…
9 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> |
11 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
AspectJ编程学习笔记
AOP基本概念
名词 | 含义 |
切面(方面,Aspect) | 一个关注点的模块化,这个关注点实现可能横切(crosscutting)多个对象切面的例子包括:事务控制、日志记录、权限控制等在AspectJ中,切面表现为Java类,其源码具有AspectJ的特殊语法增强,… |
13 years ago
1
15
Spring与Quartz的任务调度比较
任务调度代码比较
Spring 2.x 任务调度示例
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 |
<bean id="demoJob" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!-- 目标Bean --> <property name="targetObject"> <bean class="cc.gmem.demo.DemoService" /> </property> <!-- 目标方法 --> <property name="targetMethod" value="doStuff" /> <!-- 防止并发执行 --> <property name="concurrent" value="false" /> </bean> <!-- 简单触发器 --> <bean id="simpleTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean"> <property name="jobDetail" ref="demoJob" /> <!-- 启动后,调度开始的时间 --> <property name="startDelay" value="0" /> <!-- 每隔2000ms调度一次 --> <property name="repeatInterval" value="2000" /> </bean> <!-- Cron触发器 --> <bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean"> <property name="jobDetail" ref="demoJob" /> <property name="cronExpression" value="15 0/2 * * * ?" /> </bean> <!-- 调度工厂Bean --> <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean"> <property name="triggers"> <list> <ref bean="simpleTrigger" /> <ref bean="cronTrigger" /> </list> </property> </bean> |
Spring 3.x 任务调度示例
配置文件方式
1 2 3 4 5 6 7 |
<!-- 任务调度器配置,pool-size为线程池大小,限制了同时最多被调度的任务 --> <task:scheduler pool-size="100" id="scheduler" /> <!-- 任务计划列表,支持固定频率、固定延迟、Cron表达式等 --> <task:scheduled-tasks scheduler="scheduler"> <task:scheduled fixed-rate="120000" method="doStuff" ref="demoService" /> <task:scheduled cron="15 0/2 * * * ?" method="doStuff" ref="demoService" /> </task:scheduled-tasks> |
Quartz任务调度示例
特性比较
比较项 | Spring2.x | Spring3.x | Quartz |
优… |
13 years ago
0
Spring知识集锦
配置
Spring各种注入方式的区别
注入方式 | 说明 |
@Resource | 来源:JSR250 (Common Annotations for Java) 注入方式:
|
13 years ago
0