2016-03-01 132 views
-1

我想迁移我的spring mvc hibernate configuration到 。 我附加我的配置文件,用于beans configuration。但我想玩Spring引导。请帮助我在Spring引导中迁移我的应用程序。添加春季启动到我的春天mvc休眠应用

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

} 
+1

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

回答

2

首先修改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的@Bean

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

@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)春季启动拥有一支由default.Also /resources是默认映射,你可以让Spring引导为网络做自动配置所以删除@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,而不是简单的冬眠,你甚至可以删除所有的休眠的东西,让春天开机采取照顾。

注:您可能需要在你的classpath作为一个依赖于“排除the HibernateJpaAutoConfiguration in the @SpringBootApplication to prevent Spring Boot from detecting the entity manager (if you accidentally happen to have休眠-entitymanager`。

注2:这只是ONE的做法是不方法,因为有多种方式导致春季启动集成到现有的应用程序

注3:根据因人而异用过的Spring版本可能需要重构应用程序的某些部分。如果你仍然在春季的旧版本,你可能会遇到不赞成的类。

+0

感谢Deinum的宝贵回复。我会根据您的回复更改我的代码。 –

+0

当然每一步测试:)。我是从头到尾做的,所以我可能错过了几件事情,但至少应该给你一些指导。 –