Интеграция Spring Boot в проект EAR

У меня есть существующий военный проект, созданный с использованием весенней загрузки. Как упаковать его в EAR с модулем EJB?

Есть ли способ переместить пакеты модели и дао в модуль EJB и внедрить его с помощью модуля WAR?


person Shakthi    schedule 07.04.2017    source источник


Ответы (3)


Вы должны использовать систему управления зависимостями.

Это позволяет вам установить родительский проект модуля Spring Boot WAR, отличный от проекта spring-boot-starter-parent. Тогда можно было бы включить проект WAR в проект EAR так же, как и любой другой.

<dependencyManagement>
     <dependencies>
        <dependency>
            <!-- Import dependency management from Spring Boot -->
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-dependencies</artifactId>
            <version>1.5.2.RELEASE</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

... теперь вы можете использовать все стартовые зависимости Spring Boot обычным способом:

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

Начальные зависимости вы должны указывать на уровне проектов модулей, тогда как конфигурация управления зависимостями может быть указана на обоих - вокруг всех EAR проектов или отдельно на каждом из них, в зависимости от требований приложения.

Использование Spring Boot без родительского POM

person WildDev    schedule 07.04.2017

Вам нужен родительский проект, который включает военный проект, который будет вашим весенним загрузочным проектом, и проект уха только для создания вашего уха.

Родитель должен иметь весеннюю загрузку в качестве родителя:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

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

  <groupId>com.greg</groupId>
  <artifactId>ear-example</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>pom</packaging>

  <properties>
        <myproject.version>1.0-SNAPSHOT</myproject.version>
  </properties>

  <name>ear-example</name>
  <modules>
    <module>example-ear</module>
    <module>example-war</module>
  </modules>

</project>

Ваш ушной проект:

<?xml version="1.0"?>
<project xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" xmlns="http://maven.apache.org/POM/4.0.0"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  <modelVersion>4.0.0</modelVersion>

  <parent>
    <groupId>com.greg</groupId>
    <artifactId>ear-example</artifactId>
    <version>1.0-SNAPSHOT</version>
  </parent>

  <artifactId>example-ear</artifactId>
  <packaging>ear</packaging>

  <dependencies>
    <dependency>
      <groupId>com.greg</groupId>
      <artifactId>example-war</artifactId>
      <version>${project.version}</version>
      <type>war</type>
    </dependency>
  </dependencies>

  <build>
   <plugins>
     <plugin>
        <artifactId>maven-ear-plugin</artifactId>
        <version>2.10.1</version>
        <configuration>
                <modules>
                        <webModule>
                                <groupId>com.greg</groupId>
                                <artifactId>example-war</artifactId>
                                <contextRoot>/appname</contextRoot>
                        </webModule>
                </modules>
        </configuration>
      </plugin>
    </plugins>
  </build>

</project>
person Essex Boy    schedule 07.04.2017
comment
также отключить конечные точки jmx: endpoints.jmx.enabled= false - person Mirlo; 01.02.2019

Я создал многомодульный проект Gradle, включающий веб-сервисы spring RESTFul. Имя приложения EAR — bluestone bluestone/settings.gradle —

rootProject.name = 'bluestone'
include ':bluestone-web'
include ':bluestone-core'
include ':bluestone-rest'

project (':bluestone-web').projectDir = new File('bluestone-web')
project (':bluestone-core').projectDir = new File('bluestone-core')
project (':bluestone-rest').projectDir = new File('bluestone-rest')

структура проекта bluestone-rest -

введите здесь описание изображения

bluestone-rest/build.gradle

plugins {
    id 'war'
}

group 'com.bluestone.smart.rest'
version '1.0-SNAPSHOT'



dependencies {
    compile library.spring_context
    compile library.spring_web
    compile library.spring_beans
    compile library.spring_mvc
    providedCompile library.servlet_api
    testCompile library.junit

}

все зависимости импортируются из общих библиотек.gradle. общие библиотеки.gradle - это пользовательское ухо bluestone/libraries.gradle

/* ============================================================================
   Library definitions for project 'Bluestone'
   ============================================================================
   Define here library dependencies and use them inside sub-modules build.gradle.

   Included from: "${rootProject.projectDir}/build.gradle"
   ============================================================================

 */
ext {

    library = [
            /* testing */
            junit: "junit:junit:4.12",
            log4j: "log4j:log4j:1.2.17",

            /* Spring libraries*/
            spring_context:					"org.springframework:spring-context:${spring_lib_version}",
            spring_aop:						"org.springframework:spring-aop:${spring_lib_version}",
            spring_beans:					"org.springframework:spring-beans:${spring_lib_version}",
            spring_orm:						"org.springframework:spring-orm:${spring_lib_version}",
            spring_web:						"org.springframework:spring-web:${spring_lib_version}",
            spring_mvc:                     "org.springframework:spring-webmvc:${spring_lib_version}",
            servlet_api:                     "javax.servlet:javax.servlet-api:4.0.1"

    ]
}

В bluestone-rest я создал три основных файла для тестирования примера сообщения об отдыхе:

  1. Spring Конфигурация с именем - BlueRestConfiguration.java

package com.bluestone.smart.rest.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScans;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"com.bluestone.smart.rest.resources", "com.bluestone.smart.rest.controller"})
public class BlueRestConfiguration {
}

  1. Файл инициализации - называется - RestInit.java

package com.bluestone.smart.rest.config;

import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;

import javax.servlet.ServletContext;

public class RestInit extends AbstractAnnotationConfigDispatcherServletInitializer {
    /**
     * Specify {@code @Configuration} and/or {@code @Component} classes for the
     * {@linkplain #createRootApplicationContext() root application context}.
     *
     * @return the configuration for the root application context, or {@code null}
     * if creation and registration of a root context is not desired
     */
    @Override
    protected Class<?>[] getRootConfigClasses() {
        return new Class[] {BlueRestConfiguration.class};
    }

    /**
     * Specify {@code @Configuration} and/or {@code @Component} classes for the
     * {@linkplain #createServletApplicationContext() Servlet application context}.
     *
     * @return the configuration for the Servlet application context, or
     * {@code null} if all configuration is specified through root config classes.
     */
    @Override
    protected Class<?>[] getServletConfigClasses() {
        return null;
    }

    /**
     * Specify the servlet mapping(s) for the {@code DispatcherServlet} &mdash;
     * for example {@code "/"}, {@code "/app"}, etc.
     *
     * @see #registerDispatcherServlet(ServletContext)
     */
    @Override
    protected String[] getServletMappings() {
        return new String[] {"/"};
    }
}

  1. API-интерфейс службы отдыха — с именем — GreetingsController.java

package com.bluestone.smart.rest.resources;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class GreetingsController {
    @RequestMapping(path = "/greeting", method = RequestMethod.GET)
    public String greetings(){
        return "Welcome Spring Rest!";
    }
}

наконец, создайте это приложение EAR, используя -

gradlew clean build 

и разверните приложение WildFly, а затем вызовите эту службу с помощью почтальона — введите здесь описание изображения

Пожалуйста, дайте мне знать, если требуется дополнительная информация. Я отправлю этот код на git и поделюсь ссылкой на git здесь.

person Pravind Kumar    schedule 28.07.2019