【问题标题】:Spring XML Config to Java ConfigSpring XML 配置到 Java 配置
【发布时间】:2023-03-21 05:26:02
【问题描述】:

在我当前的应用程序中,我已经在 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("/");
    }

对于休眠持久性配置:

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

【问题讨论】:

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


    【解决方案1】:

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

    首先,您需要一个初始化程序。您创建的扩展 WebApplicationInitializerBootstrap 类是一种方法。

    现在,要将 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。

    希望这会有所帮助。

    【讨论】:

    • 谢谢。所以我只需要将每个xml bean转换为java方法并用@bean标记。
    猜你喜欢
    • 2012-10-19
    • 2017-06-21
    • 1970-01-01
    • 2013-10-24
    • 2016-10-24
    • 2015-11-19
    • 2015-05-30
    • 2011-01-15
    • 2014-04-18
    相关资源
    最近更新 更多