简体   繁体   中英

Add Spring boot into my spring mvc hibernate application

I would like to migrate my spring mvc hibernate configuration into spring boot . I am attaching my configuration file which is used to beans configuration . But i want to play with Spring boot. Please help me to migrate my application in 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();
    }

}

First modify your pom and add the spring-boot-starter-parent as a parent.

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

And add the spring-boot-maven-plugin as a plugin to your build.

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

Now you have the basic build blocks and you can start adding Spring Boot starters and reduce your configuration. First add a the spring-boot-starter-web dependency.

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

Now you can remove the javax.servlet and spring-web dependencies those will be added by the spring-boot-starter-web dependency.

Now you need a starter class to have an embedded container running.

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

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

Now you have a Spring Boot application with an embedded tomcat. Spring Boot should be smart enough in detecting which beans are already there and which dependencies you have.

Now you can start removing things from your configuration and let Spring Boot handle them for you.

First you can remove the PropertySourcesPlaceholderConfigurer bean as Spring Boot already provides that. You can also remove the @PropertySource as Spring Boot already loads that by default. The same applies to @EnableTransactionManagement .

Now the easiest thing to do is to start with the datasource. Rename the db.* properties to spring.datasource.* properties. This will let Spring Boot know you want it to configure a DataSource . When done, remove all properties related to the database and the @Bean for the `DataSource.

You can then simply modify your getSessionFactory method (I would remove the get part btw).

@Bean
public SessionFactory getSessionFactory(DataSource dataSource) {

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

This will already cleanup your configuration.

Now if your messageSource is using messages as a basename you can even remove the messageSource bean as Spring Boot provides one by default. If you have another base name specify it by adding the spring.messages.basename=your-basename and spring.messages.encoding=your-encoding . (And again another bean bites the dust).

You are using thyme leaf, add the spring-boot-thymeleaf-starter remove the beans for Thymeleaf and add the following the application.properties .

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

You can also remove the InternalResourceViewResolver (looks like your XmlViewResolver isn't a bean anyway) Spring Boot has one by default.Also /resources is mapped by default and you can let Spring Boot do auto configuring for the web so remove @EnableWebMvc as well.

In the end your configuration would look something like this

@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());    
    }
}

If you would move to JPA instead of plain hibernate you could even remove all of the hibernate stuff and let spring boot take care of that.

Note: You might need to 'exclude the HibernateJpaAutoConfiguration in the @SpringBootApplication to prevent Spring Boot from detecting the entity manager (if you accidentally happen to have hibernate-entitymanager` on your classpath as a dependency.

Note 2: This is just ONE approach it isn't THE approach as there are multiple ways leading to integrating Spring Boot into an existing application

Note 3: YMMV depending on the used Spring version you might need to refactor parts of your application. If you are still on an old version of spring you might run into deprecated classes for instance.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM