很久之前写过两篇博客:
spring3.0使用annotation完全代替XML

spring3.0使用annotation完全代替XML(续)

用java config来代替XML,当时还遗留下一些问题:

  • <tx:annotation-driven />声明性事务等配置无法用简单代码来实现
  • web.xml无法去掉

随着servlet 3.0规范以及spring3.1.M2的发布,现在以上的问题也解决了。

先来说说web.xml,有两种方法来替代

(一)annotation

  1. @WebServlet(urlPatterns="/hello")
  2. public class HelloServlet extends HttpServlet {}

servlet3.0增加了@WebServlet, @WebFilter,
@WebListener等注解,servlet容器会在classpath扫描并注册所有的标注好的servlet,
filter和listener。这种方法只针对你能访问源代码的情况,对于像spring_mvc用到的DispatcherServlet,无法在源码上加annotation,可以用第二种方法来实现bootstrap

(二)ServletContainerInitializer

这是servlet3的一个接口,我们来看看spring-web提供的实现

  1. @HandlesTypes(WebApplicationInitializer.class)
  2. public class SpringServletContainerInitializer implements ServletContainerInitializer {
  3. public void onStartup(Set<Class<?>> webAppInitializerClasses,
  4. ServletContext servletContext) throws ServletException {
  5. //implemention omitted
  6. }
  7. }

@HandlesTypes也是servlet3中的注解,这里它处理的是WebApplicationInitializer,也就是说servlet容器会扫描classpath,将所有实现了WebApplicationInitializer接口的类传给onStartup方法中的webAppInitializerClasses,并调用onStartup方法来注册servlet。具体的注册代码可以这样写:

  1. public class WebInit implements WebApplicationInitializer {
  2. @Override
  3. public void onStartup(ServletContext sc) throws ServletException {
  4. sc.addFilter("hibernateFilter", OpenSessionInViewFilter.class).addMappingForUrlPatterns(null, false, "/*");
  5. // Create the 'root' Spring application context
  6. AnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();
  7. root.scan("septem.config.app");
  8. // Manages the lifecycle of the root application context
  9. sc.addListener(new ContextLoaderListener(root));
  10. AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
  11. webContext.setConfigLocation("septem.config.web");
  12. ServletRegistration.Dynamic appServlet = sc.addServlet("appServlet", new DispatcherServlet(webContext));
  13. appServlet.setLoadOnStartup(1);
  14. appServlet.addMapping("/");
  15. }
  16. }

以上的代码分别调用了sc.addFilter, sc.addListener, sc.addServlet来注册filter, listener和servlet.

用以上的方法就能将WEB-INF/web.xml删除了.spring3.1.M2开始增加了一系列annotation来实现声明性事务及简化spring_mvc配置。WebInit中注册的DispatcherServlet所对应的配置在septem.config.web包里面:

  1. @Configuration
  2. @ComponentScan(basePackages="septem.controller")
  3. @EnableWebMvc
  4. public class WebConfig {
  5. }

一行@EnableWebMvc就导入了spring_mvc需要的诸多bean,再配合@ComponentScan扫描septem.controller包里面所有的@Controller,基本的mvc配置就完成了。

声明性事务也是类似,通过spring root application context扫描包septem.config.app:

  1. @Configuration
  2. @EnableTransactionManagement
  3. public class DataConfig {
  4. @Bean public AnnotationSessionFactoryBean sessionFactory() {
  5. AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
  6. sessionFactoryBean.setDataSource(dataSource());
  7. sessionFactoryBean.setNamingStrategy(new ImprovedNamingStrategy());
  8. sessionFactoryBean.setPackagesToScan("septem.model");
  9. sessionFactoryBean.setHibernateProperties(hProps());
  10. return sessionFactoryBean;
  11. }
  12. private DataSource dataSource() {
  13. BasicDataSource source = new BasicDataSource();
  14. source.setDriverClassName("org.hsqldb.jdbcDriver");
  15. source.setUrl("jdbc:hsqldb:mem:s3demo_db");
  16. source.setUsername("sa");
  17. source.setPassword("");
  18. return source;
  19. }
  20. @Bean public HibernateTransactionManager transactionManager() {
  21. HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager();
  22. hibernateTransactionManager.setSessionFactory(sessionFactory().getObject());
  23. return hibernateTransactionManager;
  24. }
  25. private Properties hProps() {
  26. Properties p = new Properties();
  27. p.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");
  28. p.put("hibernate.cache.use_second_level_cache", "true");
  29. p.put("hibernate.cache.use_query_cache", "true");
  30. p.put("hibernate.cache.provider_class",
  31. "org.hibernate.cache.EhCacheProvider");
  32. p.put("hibernate.cache.provider_configuration_file_resource_path",
  33. "ehcache.xml");
  34. p.put("hibernate.show_sql", "true");
  35. p.put("hibernate.hbm2ddl.auto", "update");
  36. p.put("hibernate.generate_statistics", "true");
  37. p.put("hibernate.cache.use_structured_entries", "true");
  38. return p;
  39. }
  40. }

DataConfig定义了所有与数据库和hibernate相关的bean,通过@EnableTransactionManagement实现声明性事务。

service是如何注册的呢?

  1. @Configuration
  2. @ComponentScan(basePackages="septem.service")
  3. public class AppConfig {
  4. }

通过@ComponentScan扫描包septem.service里定义的所有service,一个简单service实现如下:

  1. @Service @Transactional
  2. public class GreetingService {
  3. @Autowired
  4. private SessionFactory sessionFactory;
  5. @Transactional(readOnly=true)
  6. public String greeting() {
  7. return "spring without xml works!";
  8. }
  9. @Transactional(readOnly=true)
  10. public Book getBook(Long id) {
  11. return (Book) getSession().get(Book.class, id);
  12. }
  13. @Transactional(readOnly=true)
  14. public Author getAuthor(Long id){
  15. return (Author) getSession().get(Author.class, id);
  16. }
  17. public Book newBook() {
  18. Book book = new Book();
  19. book.setTitle("java");
  20. getSession().save(book);
  21. return book;
  22. }
  23. public Author newAuthor() {
  24. Book book = newBook();
  25. Author author = new Author();
  26. author.setName("septem");
  27. author.addBook(book);
  28. getSession().save(author);
  29. return author;
  30. }
  31. private Session getSession() {
  32. return sessionFactory.getCurrentSession();
  33. }
  34. }

这样整个项目中就没有XML文件了。在写这些代码的过程中也碰到不少问题,纪录如下:

(一)项目没有web.xml,maven的war插件要加上failOnMissingWebXml=false

  1. <plugin>
  2. <groupId>org.apache.maven.plugins</groupId>
  3. <artifactId>maven-war-plugin</artifactId>
  4. <version>2.1.1</version>
  5. <configuration>
  6. <failOnMissingWebXml>false</failOnMissingWebXml>
  7. </configuration>
  8. </plugin>

(二) tomcat-embeded7.0.16还有点小BUG,不能把DispatcherServlet映射为"/",所以代码里把它映射为"/s3/"

  1. appServlet.addMapping("/s3/");

(三) 如果要使用spring提供的OpenSessionInViewFilter,在定义Hibernate SessionFactory的时候,不能直接new SessionFactory出来,即以下代码是不能实现声明性事务的:

  1. @Bean public SessionFactory sessionFactory() {
  2. org.hibernate.cfg.Configuration config = new org.hibernate.cfg.Configuration();
  3. config.setProperties(hProps());
  4. config.addAnnotatedClass(Book.class);
  5. return config.buildSessionFactory();
  6. }

必须使用spring提供的FactoryBean:

  1. @Bean public AnnotationSessionFactoryBean sessionFactory() {
  2. AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean();
  3. sessionFactoryBean.setDataSource(dataSource());
  4. sessionFactoryBean.setNamingStrategy(new ImprovedNamingStrategy());
  5. sessionFactoryBean.setPackagesToScan("septem.model");
  6. sessionFactoryBean.setHibernateProperties(hProps());
  7. return sessionFactoryBean;
  8. }

后记:在spring3.1以servlet3中annotation已经是一等公民了,可以实现任何原先只能在xml文件中配置的功能,并具有简洁,静态检查及重构友好等优点。总体上来讲spring提供的“魔法”还是太多了,尤其是跟hibernate,事务,open
session in
view等机制结合在一起的时候,简洁代码的背后隐藏着太多的依赖关系,如果程序出了问题,排除这些魔法,一层一层地还原程序的本来面目,将是一件很需要耐心的事情

spring3.0使用annotation完全代替XML(三)的更多相关文章

  1. spring3.0使用annotation完全代替XML

    @Service与@Component有什么不同?那天被问到这个问题,一时之间却想不起来,就利用这篇文章来纪录spring3.0中常用的annotation. 从spring2.5开始,annotat ...

  2. spring3.0使用annotation完全代替XML(续)

    从回帖的反应来看,大多数人还是不赞成完全代替XML的,这点倒是在意料之中.我个人还是倾向于用代码来取代XML的Bean定义,当然这更多的是关乎个人偏好,不代表与我观点不同的人就是错的. 先来说说代码相 ...

  3. 缓存初解(三)---Spring3.0基于注解的缓存配置+Ehcache和OScache

    本文将构建一个普通工程来说明spring注解缓存的使用方式,关于如何在web应用中使用注解缓存,请参见: Spring基于注解的缓存配置--web应用实例 一.简介 在spring的modules包中 ...

  4. 开发基础框架:mybatis-3.2.8 +hibernate4.0+spring3.0+struts2.3

    一:项目下载地址(点击 Source code(zip)) https://github.com/fzxblgong/frame_2014-12-15/releases 版本:v1.2大小:20M 二 ...

  5. MyEclipse-10.0下Struts2.1+Spring3.0+Hibernate3.3整合过程

    新建web project: 命名为SSH,做如下设置: 新建后的工程目录如下: 然后开始添加SSH框架,这里我按照struts-spring-hibernate顺序进行添加. 首先添加struts2 ...

  6. Spring3.0 与 MyBatis框架 整合小实例

    本文将在Eclipse开发环境下,采用Spring MVC + Spring + MyBatis + Maven + Log4J 框架搭建一个Java web 项目. 1. 环境准备: 1.1 创建数 ...

  7. spring3.0+Atomikos 构建jta的分布式事务 -- NO

    摘自: http://gongjiayun.iteye.com/blog/1570111 spring3.0+Atomikos 构建jta的分布式事务 spring3.0已经不再支持jtom了,不过我 ...

  8. Jbpm4.4+hibernate3.5.4+spring3.0.4+struts2.1.8整合例子(附完整的请假流程例子,jbpm基础,常见问题解决)

    Jbpm4.4+hibernate3.5.4+spring3.0.4+struts2.1.8 整合例子(附完整的请假流程例子). 1.jbpm4.4 测试环境搭建 2.Jbpm4.4+hibernat ...

  9. spring3.0+Atomikos 构建jta的分布式事务

    摘自: http://gongjiayun.iteye.com/blog/1570111 spring3.0+Atomikos 构建jta的分布式事务 spring3.0已经不再支持jtom了,不过我 ...

随机推荐

  1. [转]python 常用类库!

    Python学习 On this page... (hide) 1. 基本安装 2. Python文档 2.1 推荐资源站点 2.2 其他参考资料 2.3 代码示例 3. 常用工具 3.1 Pytho ...

  2. 设计模式--组合模式Composite(结构型)

    一.概念 组合模式允许你将对象组合成树形结构来表现"整体/部分"层次结构.组合能让客户以一致的方式处理个别对象以及对象组合. 二.UML图 1.Component(对象接口),定义 ...

  3. Windows Server 2008 双网卡同时上内外网 不能正常使用

    Windows server 2008 32位下,双网卡同时上内外网,并提供VPN服务,遇见的奇怪问题 1.服务器配置 2.网络配置 以太网适配器 内部连接: 连接特定的 DNS 后缀 . . . . ...

  4. ssl访问的原理

    本文无图文对照解释,但力求通俗易懂.请读者边读边手绘各个流程,一便于理解.      总体交互流程如下      1. 客户端发起HTTPS请求 这个没什么好说的,就是用户在浏览器里输入一个https ...

  5. CentOS7 编译安装 nginx-1.10.0

    对于NGINX 支持epoll模型 epoll模型的优点 定义: epoll是Linux内核为处理大批句柄而作改进的poll,是Linux下多路复用IO接口select/poll的增强版本,它能显著的 ...

  6. 总结一下项目中遇到的分页问题,使用bootstrap-table来做的后台分页,大家可以借鉴一下 (分页第一篇)

    前台进入bootstrap的js和css文件,我就不多少了,另外要引进bootstrap-table的js和css 废话不多说,直接代码.   框架为ssm,代码很清楚 <div class=& ...

  7. 忘记mysq rootl密码

    忘记mysq rootl密码 1       mysql忘记root密码 1.1     查看mysql的进程 [root@mysql data]# cat /data/mysql.localdoma ...

  8. 阿里云centos7基于搭建VPN

    本文参考自:http://www.xxkwz.cn/1495.html 前段时间使用pptp搭建了一个VPN,速度很快,但是用了大概一个月挂了,估计是被墙了吧,于是,用shadowsocks重新搭建了 ...

  9. js实现返回顶部功能的解决方案

    很多网站上都有返回顶部的效果,主要有如下几种解决方案. 1.纯js,无动画版本 window.scrollTo(x-coord, y-coord); window.scrollTo(0,0); 2.纯 ...

  10. Delphi控件之---通过编码学习TStringGrid(也会涉及到Panel控件,还有对Object Inspector的控件Events的介绍

    我是参考了万一的博客里面的关于TStringGrid学习的教程,但是我也结合自己的实际操作和理解,加入了一些个人的补充,至少对我有用! 学用TStringGrid之——ColCount.RowCoun ...