Spring XML配置到Java配置

时间:2015-07-30 02:19:53

标签: hibernate spring-mvc spring-java-config

在我当前的应用程序中,我在Spring Servlet和Hibernate上完成了xml配置;它按我的意愿工作。但是,看看xml文件,我真的不明白,这对于未来的开发来说是一个挑战。因此,我想将其翻译为Java配置。但是,再看看我的配置xml文件,并按照这个guide的信息让我很困惑。那么有人会帮助我引导我的应用程序吗?

这是我的root-context.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
</beans>

servlet的contenxt.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
    /*Omit some code here*/   >


<context:component-scan base-package="com.core.domain" />
<context:component-scan base-package="com.core.dao.generic" />
<context:component-scan base-package="com.core.dto" />
<context:component-scan base-package="com.web.page" />

<mvc:annotation-driven />
<mvc:default-servlet-handler/>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
    <property name="prefix">
        <value>/WEB-INF/views/</value>
    </property>
    <property name="suffix">
        <value>.jsp</value>
    </property>
</bean>

<bean id="sessionFactory" scope="singleton"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
</bean>

<bean id="multipartResolver" 
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
</bean>

<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id ="transactionManager" class = "org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory"/>
</bean>   

这是我的hibernate.cfg.xml

<hibernate-configuration>
    <session-factory>
        <property name="hibernate.connection.driver_class">org.postgresql.Driver</property>
        <property name="hibernate.connection.url">jdbc:postgresql://localhost:5432/database</property>
        <property name="hibernate.connection.username">username</property>
        <property name="hibernate.connection.password">password</property>
        <property name="connection.pool_size">1</property>
        <property name="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</property>   
        <property name="cache.provider_class">org.hibernate.cache.internal.NoCacheProvider</property>
        <property name="show_sql">true</property>

        <property name="hibernate.jdbc.batch_size">50</property>

        <property name="hibernate.c3p0.min_size">5</property>
        <property name="hibernate.c3p0.max_size">600</property>
        <property name="hibernate.c3p0.timeout">1800</property>
        <property name="hibernate.c3p0.max_statements">50</property>
        <property name="hibernate.c3p0.idle_test_period">1800</property>


        <property name="hbm2ddl.auto">update</property>


        <!-- Resources mapping --> 
        <mapping class="com.common.domain.Account"/>
    </session-factory>
</hibernate-configuration>

现在,我只能使用以下javaConfig引导程序在web.xml中获取一些配置。引导程序仍然必须读取servlet-context.xml,我尝试将其转换为java代码,但还无法执行此操作。

public class Bootstrap implements WebApplicationInitializer {

    @Override
    public void onStartup(ServletContext container)
            throws ServletException {
        AnnotationConfigWebApplicationContext rootContext = new AnnotationConfigWebApplicationContext();
        rootContext.register(RootContextConfiguration.class);
        container.addListener(new ContextLoaderListener(rootContext));


        XmlWebApplicationContext servletContext = new XmlWebApplicationContext();
        servletContext.setConfigLocation("classpath:servlet-context.xml");

         ServletRegistration.Dynamic dispatcher = container.addServlet(
                            "SpringDispatcher", new DispatcherServlet(servletContext));

         dispatcher.setLoadOnStartup(1);
         dispatcher.addMapping("/");
    }

和Hibernate Persistence Config:

public class PersistenceConfig {

    @Autowired
    private Environment env;

    @Bean
    public LocalSessionFactoryBean sessionFactory() {
        System.out.println("Create SessionFactory");
        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
        sessionFactory.setDataSource(restDataSource());
        sessionFactory.setPackagesToScan(new String[] {
                    "com.common.domain.Account"
        });
        sessionFactory.setHibernateProperties(hibernateProperties());

        return sessionFactory;
    }

    @Bean
    public DataSource restDataSource() {
        BasicDataSource dataSource = new BasicDataSource();
        dataSource.setDriverClassName(env.getProperty("org.postgresql.Driver"));
       dataSource.setUrl(env.getProperty("jdbc:postgresql://localhost:5432/app"));
       dataSource.setUsername(env.getProperty("username"));
       dataSource.setPassword(env.getProperty("password"));
        return dataSource;
    }

    /**
     * Setting up the hibernate transaction Manager
     * @param sessionFactory
     * @return
     */
     @Bean
     @Autowired
     public HibernateTransactionManager transactionManager(SessionFactory sessionFactory) {
          HibernateTransactionManager txManager = new HibernateTransactionManager();
          txManager.setSessionFactory(sessionFactory);

          return txManager;
       }

       @Bean
       public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
          return new PersistenceExceptionTranslationPostProcessor();
       }


     Properties hibernateProperties() {
          return new Properties() {
             {
                setProperty("hibernate.dialect", env.getProperty("org.hibernate.dialect.PostgreSQLDialect"));
                setProperty("hibernate.globally_quoted_identifiers", "true");
             }
          };
       }
}

1 个答案:

答案 0 :(得分:3)

有许多方法可以在Spring中创建配置文件,纯XML,纯Java或两者的组合。假设您想要用Java完成所有工作,则必须完全放弃web.xmlservlet-context.xml个文件。但请注意,web.xml中有一些条目AFAIK无法转换为Java代码。

首先,您需要一个初始化程序。您制作的Bootstrap课程扩展WebApplicationInitializer是一种方法。

现在,要将servlet-context.xml转换为Java,你应该有一个看起来像这样的类(无关紧要):

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.core.domain", "com.core.dao.generic" /* OTHER PACKAGES CONTAINING @Controller */})
@Transactional
public class WebMvcConfig extends WebMvcConfigurerAdapter {

  @Bean
  public ViewResolver jspViewResolver() {
    InternalResourceViewResolver jspViewResolver = new InternalResourceViewResolver();
    jspViewResolver.setPrefix("/WEB-INF/views/");
    jspViewResolver.setSuffix(".jsp");
    return jspViewResolver;
  }

  @Bean
  @Scope(value = "singleton")     /* Actually, default is singleton */
  public SessionFactory sessionFactory() {
    LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();
    sessionFactory.setConfigLocation("classpath:hibernate.cfg.xml");
    return sessionFactory.getObject();
  }

  @Bean
  public MultipartResolver multipartResolver() {
    return new CommonsMultipartResolver();
  }

  @Bean   /* This should be present when using @Transactional (see annotations above) */
  public TransactionManager tx() {
    HibernateTransactionManager tx = new HibernateTransactionManager();
    tx.setSessionFactory(this.sessionFactory());
    return tx();
  }

  @Override
  public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
    configurer.enable();
  }
}

这将是servlet-context.xml的等效Java代码。确保将其传递给初始化程序,以便可以初始化和正确使用Bean。这意味着您需要更改servletContext的类型并改为传入WebMvcConfig.class。

希望这有帮助。