【问题标题】:Add Spring boot into my spring mvc hibernate application将 Spring boot 添加到我的 spring mvc hibernate 应用程序中
【发布时间】:2016-03-01 07:22:17
【问题描述】:

我想将我的 spring mvc hibernate configuration 迁移到 spring boot。 我正在附加我用于beans configuration 的配置文件。但我想玩 Spring boot。请帮助我在 Spring Boot 中迁移我的应用程序。

Config.java

import java.util.Properties;

import javax.annotation.Resource;

import org.apache.commons.dbcp2.BasicDataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.context.support.ReloadableResourceBundleMessageSource;
import org.springframework.core.env.Environment;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBuilder;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.XmlViewResolver;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver;

@Configuration
@ComponentScan("")
@EnableWebMvc
@EnableTransactionManagement
@PropertySource("classpath:application.properties")
public class Config extends WebMvcConfigurerAdapter {

    @Value("${db.driver}")
    private String dbDriver;

    @Value("${db.url}")
    private String dbUrl;

    @Value("${db.username}")
    private String dbUserName;

    @Value("${db.password}")
    private String dbPassword;

    @Value("${hibernate.dialect}")
    private String dialect;

    @Value("${hibernate.hbm2ddl.auto}")
    private String hbmddl;

    @Value("${message.basename}")
    private String baseName;

    @Value("${message.encoding}")
    private String encoding;

    @Value("${hibernate.connection.datasource}")
    private String datasource;

    @Resource
    private Environment environment;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/resources/**").addResourceLocations("/resources/");
    }

    public XmlViewResolver XmlViewResolver() {

        XmlViewResolver xmlViewResolver = new XmlViewResolver();
        return xmlViewResolver;
    }

    @Bean
    public InternalResourceViewResolver setupViewResolverForRedirect() {
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();

        resolver.setViewNames(new String[] { "redirect*" });
        return resolver;
    }

    @Bean
    public CommonsMultipartResolver multipartResolver() {
        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        // commonsMultipartResolver.setMaxUploadSize(1048576);
        commonsMultipartResolver.setMaxUploadSize(10000000);
        return commonsMultipartResolver;
    }

    @Bean
    public TemplateResolver templateResolver() {
        ServletContextTemplateResolver templateResolver = new ServletContextTemplateResolver();
        templateResolver.setPrefix("/WEB-INF/views/");
        templateResolver.setSuffix(".html");
        templateResolver.setCacheable(false);
        templateResolver.setTemplateMode("HTML5");

        return templateResolver;
    }

    @Bean
    public SpringTemplateEngine templateEngine() {
        SpringTemplateEngine templateEngine = new SpringTemplateEngine();
        templateEngine.setTemplateResolver(templateResolver());
        return templateEngine;
    }

    @Bean
    public ThymeleafViewResolver viewResolver() {
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(templateEngine());
        return viewResolver;
    }

    @Bean(name = "messageSource")
    public ReloadableResourceBundleMessageSource getMessageSource() {
        ReloadableResourceBundleMessageSource resource = new ReloadableResourceBundleMessageSource();

        resource.setBasename(baseName);
        resource.setDefaultEncoding(encoding);
        return resource;
    }

    @Bean
    public SessionFactory getSessionFactory() {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(getDataSource());

        sessionBuilder.addProperties(getHibernateProperties());

        sessionBuilder.addAnnotatedClass(com.aaaa.Example.class);

        return sessionBuilder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {
        Properties properties = new Properties();
        properties.put("hibernate.show_sql", true);
        properties.put("hibernate.dialect", dialect);

        if (datasource!=null && !datasource.equalsIgnoreCase("")) {
            properties.put("hibernate.connection.datasource",datasource);
        }

        properties.put("hibernate.hbm2ddl.auto", hbmddl);


        return properties;
    }

    @Bean
    public BasicDataSource getDataSource() {
        BasicDataSource dataSource = new BasicDataSource();

        dataSource.setDriverClassName(dbDriver);
        dataSource.setUrl(dbUrl);
        dataSource.setUsername(dbUserName);
        dataSource.setPassword(dbPassword);

        return dataSource;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager(getSessionFactory());

        return transactionManager;
    }

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertyConfig() {
        return new PropertySourcesPlaceholderConfigurer();
    }

}

【问题讨论】:

  • 只需将 spring-boot-starter-data-jpa 依赖添加到您的 pom 文件中即可摆脱此配置。 jpa starter 提供了一个底层的 Hibernate 实现,它可以从你的 application.properties 文件中配置。看一下boot的jpa属性:docs.spring.io/spring-boot/docs/current/reference/html/…

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


【解决方案1】:

首先修改您的 pom 并将 spring-boot-starter-parent 添加为父级。

<parent>
    <groupId>org.springframework.boot</groupId>
    <artificatId>spring-boot-starter-parent</artifactId>
    <version>1.3.3.RELEASE</version>
</parent>

并将spring-boot-maven-plugin 作为插件添加到您的构建中。

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

现在你已经有了基本的构建块,你可以开始添加 Spring Boot 启动器并减少你的配置。首先添加一个spring-boot-starter-web 依赖。

<dependency>
    <groupId>org.springframework.boot</groupId>
    < artifactId >spring-boot-starter-web</artifactId>
</dependency>

现在您可以删除 javax.servletspring-web 依赖项,它们将由 spring-boot-starter-web 依赖项添加。

现在您需要一个启动类来运行嵌入式容器。

@SpringBootApplication
@Import(Config.class) 
public class YourApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(YourApplication.class, args);
    }
}

现在您有了一个带有嵌入式 tomcat 的 Spring Boot 应用程序。 Spring Boot 应该足够聪明地检测哪些 bean 已经存在以及您拥有哪些依赖项。

现在你可以开始从你的配置中删除一些东西,让 Spring Boot 为你处理它们。

首先,您可以删除 PropertySourcesPlaceholderConfigurer bean,因为 Spring Boot 已经提供了它。您还可以删除 @PropertySource,因为默认情况下 Spring Boot 已经加载了它。这同样适用于@EnableTransactionManagement

现在最简单的事情是从数据源开始。将 db.* 属性重命名为 spring.datasource.* 属性。这会让 Spring Boot 知道你希望它配置一个DataSource。完成后,删除与数据库相关的所有属性和 `DataSource.xml 的 @Bean

然后您可以简单地修改您的 getSessionFactory 方法(顺便说一句,我会删除 get 部分)。

@Bean
public SessionFactory getSessionFactory(DataSource dataSource) {

    LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);   
    sessionBuilder.addProperties(getHibernateProperties());    
    sessionBuilder.addAnnotatedClass(com.aaaa.Example.class);
    return sessionBuilder.buildSessionFactory();
}

这已经清理了您的配置。

现在,如果您的 messageSource 使用 messages 作为基本名称,您甚至可以删除 messageSource bean,因为 Spring Boot 默认提供一个。如果您有另一个基本名称,请通过添加 spring.messages.basename=your-basenamespring.messages.encoding=your-encoding 来指定它。 (又一个豆子咬了灰尘)。

您正在使用百里香叶,添加spring-boot-thymeleaf-starter 删除Thymeleaf 的豆子并添加以下application.properties

spring.thymeleaf.prefix=/WEB-INF/views/
spring.thymeleaf.suffix=.html

你也可以删除InternalResourceViewResolver(看起来你的XmlViewResolver不是一个bean)Spring Boot默认有一个。另外/resources是默认映射的,你可以让Spring Boot自动配置网络所以也删除@EnableWebMvc

最后你的配置看起来像这样

@Configuration
public class Config extends WebMvcConfigurerAdapter {

    @Value("${hibernate.dialect}")
    private String dialect;

    @Value("${hibernate.hbm2ddl.auto}")
    private String hbmddl;

    @Resource
    private Environment environment;

    @Bean
    public CommonsMultipartResolver multipartResolver() {

        CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver();
        // commonsMultipartResolver.setMaxUploadSize(1048576);
        commonsMultipartResolver.setMaxUploadSize(10000000);
        return commonsMultipartResolver;
    }


    @Bean
    public SessionFactory sessionFactory(DataSource dataSource) {

        LocalSessionFactoryBuilder sessionBuilder = new LocalSessionFactoryBuilder(dataSource);
        sessionBuilder.addProperties(getHibernateProperties());
        sessionBuilder.addAnnotatedClass(com.aaaa.Example.class);
        return sessionBuilder.buildSessionFactory();
    }

    private Properties getHibernateProperties() {

        Properties properties = new Properties();
        properties.put("hibernate.show_sql", true);
        properties.put("hibernate.dialect", dialect);
        properties.put("hibernate.hbm2ddl.auto", hbmddl);
        return properties;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {

        return new HibernateTransactionManager(getSessionFactory());    
    }
}

如果您要迁移到 JPA 而不是普通的 hibernate,您甚至可以删除所有的 hibernate 内容并让 spring boot 来处理。

注意:您可能需要在您的类路径中将 'excludetheHibernateJpaAutoConfigurationin the@SpringBootApplicationto prevent Spring Boot from detecting the entity manager (if you accidentally happen to havehibernate-entitymanager` 作为依赖项。

注意 2: 这只是 ONE 方法,它不是 THE 方法,因为有多种方法可以将 Spring Boot 集成到现有应用程序

注意 3: YMMV 取决于使用的 Spring 版本,您可能需要重构应用程序的某些部分。例如,如果您仍在使用旧版本的 spring,您可能会遇到已弃用的类。

【讨论】:

  • 感谢 Deinum 的宝贵回复。我会根据你的回复修改我的代码。
  • 当然在每一步测试之后:)。我是从头开始做的,所以我可能错过了一些事情,但它至少应该给你一些指导。
猜你喜欢
  • 2019-03-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-09
  • 2019-01-22
  • 1970-01-01
  • 2021-04-24
  • 2014-08-22
相关资源
最近更新 更多