Spring XML 配置到 Java 配置

Spring XML Config to Java Config

在我目前的应用程序中,我已经对 Spring Servlet 和 Hibernate 进行了 xml 配置;它按我的意愿工作。但是,看看xml文件,我不是很理解,这对以后的开发来说是一个挑战。因此,我想将其翻译成 Java 配置。但是,再次查看我的配置 xml 文件并遵循此 guide 的信息让我很困惑。那么有人可以帮助我 bootstrap 我的申请吗?

这是我的根-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 bootstrap 获取 web.xml 中的一些配置。 bootstrap 仍然需要读取 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 持久性配置:

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");
             }
          };
       }
}

在 Spring、纯 XML、纯 Java 或两者的组合中有多种创建配置文件的方法。假设你想做 Java 中的所有事情,你必须完全放弃 web.xmlservlet-context.xml 文件。但是请注意,据我所知,web.xml 中有一些条目无法转换为 Java 代码。

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

现在,要将 servlet-context.xml 转换为 Java,您应该有一个看起来像这样的 class(不管什么名字):

@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 代码。确保将其传递给 Initializer,以便可以正确初始化和使用 Beans。这意味着您需要更改 servletContext 的类型并传入 WebMvcConfig.class。

希望对您有所帮助。