将 Spring 启动添加到我的 Spring mvc 休眠应用程序中



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

配置.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();
    }
}

首先修改你的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);
    }
}

现在你有一个带有嵌入式雄猫的 Spring 引导应用程序。Spring Boot 应该足够智能地检测哪些 bean 已经存在以及您拥有哪些依赖项。

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

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

现在最简单的方法是从数据源开始。将db.*属性重命名为spring.datasource.*属性。这将使 Spring Boot 知道您希望它配置DataSource。完成后,删除与数据库相关的所有属性和"数据源"的@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去除百里香叶的豆子,然后添加以下application.properties

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

你也可以删除InternalResourceViewResolver(看起来你的XmlViewResolver无论如何都不是豆子)Spring Boot 默认有一个。此外,默认情况下/resources是映射的,您可以让 Spring Boot 为 Web 进行自动配置,因此也请删除@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而不是普通的休眠,你甚至可以删除所有休眠的东西,让Spring boot来处理这个问题。

注意:您可能需要在类路径上"排除the HibernateJpaAutoConfiguration in the @SpringBootApplication to prevent Spring Boot from detecting the entity manager (if you accidentally happen to have hibernate-entitymanager"作为依赖项。

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

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

最新更新