spring3.0使用annotation完全代替XML(三)
很久之前写过两篇博客:
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
@WebServlet(urlPatterns="/hello")public class HelloServlet extends HttpServlet {}
@HandlesTypes(WebApplicationInitializer.class)public class SpringServletContainerInitializer implements ServletContainerInitializer {public void onStartup(Set<Class<?>> webAppInitializerClasses, ServletContext servletContext) throws ServletException {//implemention omitted}}
public class WebInit implements WebApplicationInitializer {@Overridepublic void onStartup(ServletContext sc) throws ServletException {sc.addFilter("hibernateFilter", OpenSessionInViewFilter.class).addMappingForUrlPatterns(null, false, "/*");// Create the 'root' Spring application contextAnnotationConfigWebApplicationContext root = new AnnotationConfigWebApplicationContext();root.scan("septem.config.app");// Manages the lifecycle of the root application contextsc.addListener(new ContextLoaderListener(root));AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();webContext.setConfigLocation("septem.config.web");ServletRegistration.Dynamic appServlet = sc.addServlet("appServlet", new DispatcherServlet(webContext));appServlet.setLoadOnStartup(1);appServlet.addMapping("/");}}
@Configuration@ComponentScan(basePackages="septem.controller")@EnableWebMvcpublic class WebConfig {}
@Configuration@EnableTransactionManagementpublic class DataConfig {@Bean public AnnotationSessionFactoryBean sessionFactory() { AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setNamingStrategy(new ImprovedNamingStrategy());sessionFactoryBean.setPackagesToScan("septem.model");sessionFactoryBean.setHibernateProperties(hProps()); return sessionFactoryBean; } private DataSource dataSource() {BasicDataSource source = new BasicDataSource();source.setDriverClassName("org.hsqldb.jdbcDriver");source.setUrl("jdbc:hsqldb:mem:s3demo_db");source.setUsername("sa");source.setPassword("");return source;}@Bean public HibernateTransactionManager transactionManager() { HibernateTransactionManager hibernateTransactionManager = new HibernateTransactionManager(); hibernateTransactionManager.setSessionFactory(sessionFactory().getObject()); return hibernateTransactionManager; } private Properties hProps() {Properties p = new Properties();p.put("hibernate.dialect", "org.hibernate.dialect.HSQLDialect");p.put("hibernate.cache.use_second_level_cache", "true");p.put("hibernate.cache.use_query_cache", "true");p.put("hibernate.cache.provider_class","org.hibernate.cache.EhCacheProvider");p.put("hibernate.cache.provider_configuration_file_resource_path","ehcache.xml");p.put("hibernate.show_sql", "true");p.put("hibernate.hbm2ddl.auto", "update");p.put("hibernate.generate_statistics", "true");p.put("hibernate.cache.use_structured_entries", "true");return p;}}
@Configuration@ComponentScan(basePackages="septem.service")public class AppConfig {}
@Service @Transactionalpublic class GreetingService {@Autowiredprivate SessionFactory sessionFactory;@Transactional(readOnly=true)public String greeting() {return "spring without xml works!";}@Transactional(readOnly=true)public Book getBook(Long id) {return (Book) getSession().get(Book.class, id);}@Transactional(readOnly=true)public Author getAuthor(Long id){return (Author) getSession().get(Author.class, id);}public Book newBook() { Book book = new Book(); book.setTitle("java"); getSession().save(book); return book;}public Author newAuthor() {Book book = newBook();Author author = new Author();author.setName("septem");author.addBook(book);getSession().save(author);return author;}private Session getSession() {return sessionFactory.getCurrentSession();}}
<plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-war-plugin</artifactId><version>2.1.1</version><configuration><failOnMissingWebXml>false</failOnMissingWebXml></configuration></plugin>
appServlet.addMapping("/s3/");
@Bean public SessionFactory sessionFactory() {org.hibernate.cfg.Configuration config = new org.hibernate.cfg.Configuration();config.setProperties(hProps());config.addAnnotatedClass(Book.class);return config.buildSessionFactory();}
@Bean public AnnotationSessionFactoryBean sessionFactory() { AnnotationSessionFactoryBean sessionFactoryBean = new AnnotationSessionFactoryBean(); sessionFactoryBean.setDataSource(dataSource()); sessionFactoryBean.setNamingStrategy(new ImprovedNamingStrategy());sessionFactoryBean.setPackagesToScan("septem.model");sessionFactoryBean.setHibernateProperties(hProps()); return sessionFactoryBean; }