首页 文章

Spring Boot / JPA / Hibernate,如何根据Spring配置文件切换数据库供应商?

提问于
浏览
1

我正在使用Spring Boot / JPA / Hibernate . 我想在服务器上部署时在localhost和MySQL上测试时使用HSQLDB .

在pom.xml中,我对MySQL有这种依赖:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
 </dependency>

和HSQLDB的这种依赖:

<dependency>
   <groupId>org.hsqldb</groupId>
   <artifactId>hsqldb</artifactId>
</dependency>

由于Spring Boot自动配置,我可能无法将两个依赖项都放在pom.xml中 . 但是我想在 local Spring配置文件处于活动状态时使用HSQLDB,并在 server Spring配置文件处于活动状态时使用MySQL . 理想情况下,我想只生成一个war文件并使用 mvn spring-boot:run 运行本地版本,并从war文件中部署服务器版本 .

任何的想法?

P.S . :我正在使用maven

2 回答

  • 3

    由于Spring Boot自动配置,我可能无法将两个依赖项都放在pom.xml中 .

    当然你可以同时拥有它们 . 有几种解决方案 .

    最基本的一个是拥有两个依赖项,并使用mysql数据库的设置在项目中创建 application-server.properties . 当您运行没有特定配置文件的应用程序时,Spring Boot赢得了't find any information to connect to MySQL so it' ll回退到HSQL . 在服务器上部署应用程序时,请确保启用 server 配置文件 . 两个用例都可以使用相同的工件 .

    您可以通过在生成胖jar时排除hsql依赖项来改进该解决方案 . 这样做的好处是,如果您忘记启用配置文件,您将在启动时获得异常,而不是默默使用内存数据库 . 要排除hsql,只需configure the maven plugin . 您将能够在本地运行应用程序( mvn spring-boot:run )或在IDE中运行应用程序,胖jar将只包含mysql依赖项 . 您仍然需要启用 server 配置文件 .

    如果您正在使用战争,则无法使用最后的解决方案:再次切换到jar的原因;-)

  • 4

    您需要创建 Maven Profile 而不是 spring 配置文件并按顺序添加依赖项 . 使用hsqldb依赖关系创建本地配置文件,并在开发模式下激活它 . 然后创建具有mysql依赖关系的服务器配置文件,并在打包以在服务器上部署时激活它 . 我个人更喜欢开发和发布作为命名约定(但这是我的拙见) . 然后你必须用 spring profile 快捷 maven profile

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>xyz</version>
        <configuration>
          <profiles>
            <profile>local</profile>....
    

    在当地的 Profiles 和

    <plugin>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-maven-plugin</artifactId>
        <version>1.4.1.RELEASE</version>
        <configuration>
          <profiles>
            <profile>server</profile>...
    

    在服务器配置文件中,使用此开关运行所需的配置

    mvn spring-boot:run -P[local or server]
    

    Introduction to Build Profiles

相关问题