基于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
Ubuntu下安装MySQL
Ubuntu 14.04
安装必要的软件
1 2 3 |
sudo apt-get install mysql-server #修改root密码 mysqladmin -uroot -p原密码 password 新密码 |
注意,如果下载tar.gz的压缩包,需要手工进行数据库的初始化:
1 |
"scripts"/mysql_install_db --user=mysql --basedir=/var/mysql/ --datadir=/var/mysql/data/ --defaults-file=/path-to/my.cnf |
修改配置文件
创建用户并授权
禁止开机启动
容器化
Dockerfile:
创建容器的命令:
阅读全文
12 years ago
0
Linux目录层次和配置文件
/
唯一的根目录,没有Windows的盘符概念。根目录下的任何一个子目录都可以作为一个挂载点(mount point)来挂载某个文件系统(例如分区)。
/proc
即procfs,包含系统中正在运行的进程的映射文件,以及对应其它功能的若干子目录。
/proc/up…
阅读全文
13 years ago
0