简体   繁体   English

将Spring Boot集成到独立的现有Spring Jar中

[英]Integrate Spring boot into existing spring jar standalone

I have problems integrating spring boot into my existing spring project. 我在将Spring Boot集成到现有Spring项目中时遇到问题。 There are tree questions I have, but before I come to these, let me explain my current architecture: 我有一些树状问题,但是在开始讨论这些问题之前,让我先解释一下当前的体系结构:

Current project 当前的项目

I have two projects. 我有两个项目。 The first one is called myProject.toolkit and has only a main class in witch I implemented an endless do-while loop. 第一个叫做myProject.toolkit ,在我实现无休止的do-while循环的过程中只有一个主类。 This loop creates a ProcessBuilder in order to start a new process. 该循环创建一个ProcessBuilder以便开始一个新的过程。 And when this process terminates it checks whether or whether not this exit was wanted or not. 当该过程终止时,它检查是否需要此出口。 If so, it terminates. 如果是这样,它将终止。 If not, it starts the same process again (not very beautiful, but I am still learning and maybe I have an better idea in the future). 如果没有,它将再次开始相同的过程(不是很漂亮,但我仍在学习,也许将来我会有更好的主意)。
The second project is called myProject.dependencies and this is the program that will be started from the toolkit inside the loop. 第二个项目称为myProject.dependencies ,这是将从循环内的工具箱启动的程序。 This is also the real project because the toolkit only has the purpose to monitor over it. 这也是真实的项目,因为该工具包仅用于监视它。

Both projects are maven projects that are compiled to standalone jar files using aspectJ. 这两个项目都是Maven项目,可以使用AspectJ编译为独立的jar文件。
myProject.dependencies has sprint boot, hibernate and jpa. myProject.dependencies具有sprint引导,休眠和jpa。 Everything is working fine with my MySQL database. 我的MySQL数据库一切正常。 I can create Services, that will use Repositories in order to persistant Entities. 我可以创建服务,该服务将使用存储库来持久化实体。

For this I created a class called JpaConfig that has all the needed configurations in it because xml files didn't work. 为此,我创建了一个名为JpaConfig的类,其中包含所有必需的配置,因为xml文件不起作用。 It looks shortened like this: 它看起来像这样缩短:

@EnableScheduling
@EnableAsync
@EnableTransactionManagement(mode = AdviceMode.ASPECTJ)
@ComponentScan(basePackages = {"myProject"})
@Configuration
@EnableJpaRepositories
public class JpaConfig { 

    @Bean
    public InstrumentationLoadTimeWeaver loadTimeWeaver(){
        return new InstrumentationLoadTimeWeaver();
    }

    @Bean
    public DataSource dataSource(){
        // creates, configures and returnes a "BoneCPDataSource" Object
    }

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
        // creates, configures and returnes a "LocalContainerEntityManagerFactoryBean" Object
    }

    @Bean
    public JpaTransactionManager transactionManager(){
        // creates, configures and returnes a "JpaTransactionManager" Object
    }

}

In my main class of the myProject.dependencies project I call one magic line in order to get spring working: myProject.dependencies项目的主类中,我调用了一条魔术线以使Spring工作:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JpaConfig.class);

With this line the configuration gets loaded and I can use hibernate, jpa and spring with all its functionality. 通过这一行,配置被加载,我可以使用hibernate,jpa和spring及其所有功能。

integrating spring boot 集成弹簧靴

Now I want to add spring boot to the project because I need a REST API. 现在,我想将Spring Boot添加到项目中,因为我需要一个REST API。 And because I read that spring boot can run without a tomcat or glassfish and also within a jar and not a war, I thought this is the perfect architecture for me. 而且因为我听说弹簧靴可以在没有雄猫或玻璃鱼的情况下运行,也可以在罐子中而不是战争中运行,所以我认为这对我来说是理想的架构。

So I read some articles in order to verify this and on the point that I found out spring boot brings an own integrated tomcat, I tried to implement it in my existing project. 因此,我阅读了一些文章以验证这一点,并发现Spring Boot带来了自己的集成tomcat,我试图在现有项目中实现它。

I added the following dependencies to my pom.xml : 我在pom.xml添加了以下依赖项:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <version>1.4.1.RELEASE</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId> 
        <artifactId>spring-boot-starter-tomcat</artifactId> 
        <version>1.4.1.RELEASE</version>
        <!--<scope>provided</scope>-->
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
        <version>1.4.1.RELEASE</version>
    </dependency>

And because I could not set a parent pom (I already have a parent set and multiple parents are not possible in maven), I also added this to my pom without understanding it, but since these lines are also in org.springframework.boot:spring-boot-starter-parent:1.4.1.RELEASE and everyone told me to rely on this configuration, I added it: 并且因为我无法设置父pom(我已经有一个父集,并且在maven中不可能有多个父集),所以我也将其添加到pom中却不了解它,但是由于这些行也位于org.springframework.boot:spring-boot-starter-parent:1.4.1.RELEASE ,每个人都告诉我要依靠此配置,我添加了它:

    <pluginManagement>
        <plugins>
            <!-- Apply more sensible defaults for user projects -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-failsafe-plugin</artifactId>
                <version>2.19.1</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>integration-test</goal>
                            <goal>verify</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-jar-plugin</artifactId>
                <configuration>
                    <archive>
                        <manifest>
                            <mainClass>${start-class}</mainClass>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <configuration>
                    <includes>
                        <include>**/*Tests.java</include>
                        <include>**/*Test.java</include>
                    </includes>
                    <excludes>
                        <exclude>**/Abstract*.java</exclude>
                    </excludes>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-war-plugin</artifactId>
                <version>3.0.0</version>
                <configuration>
                    <failOnMissingWebXml>false</failOnMissingWebXml>
                    <archive>
                        <manifest>
                            <mainClass>${start-class}</mainClass>
                            <addDefaultImplementationEntries>true</addDefaultImplementationEntries>
                        </manifest>
                    </archive>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.codehaus.mojo</groupId>
                <artifactId>exec-maven-plugin</artifactId>
                <configuration>
                    <mainClass>${start-class}</mainClass>
                </configuration>
            </plugin>
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-resources-plugin</artifactId>
                <version>2.6</version>
                <configuration>
                    <delimiters>
                        <delimiter>${resource.delimiter}</delimiter>
                    </delimiters>
                    <useDefaultDelimiters>false</useDefaultDelimiters>
                </configuration>
            </plugin>
            <plugin>
                <groupId>pl.project13.maven</groupId>
                <artifactId>git-commit-id-plugin</artifactId>
                <version>2.1.11</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>revision</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <verbose>true</verbose>
                    <dateFormat>yyyy-MM-dd'T'HH:mm:ssZ</dateFormat>
                    <generateGitPropertiesFile>true</generateGitPropertiesFile>
                    <generateGitPropertiesFilename>${project.build.outputDirectory}/git.properties</generateGitPropertiesFilename>
                </configuration>
            </plugin>
            <!-- Support our own plugin -->
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <version>1.4.1.RELEASE</version>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
                <configuration>
                    <mainClass>${start-class}</mainClass>
                </configuration>
            </plugin>
            <!-- Support shade packaging (if the user does not want to use our plugin) -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-shade-plugin</artifactId>
                <version>2.4.3</version>
                <dependencies>
                    <dependency>
                        <groupId>org.springframework.boot</groupId>
                        <artifactId>spring-boot-maven-plugin</artifactId>
                        <version>1.4.0.BUILD-SNAPSHOT</version>
                    </dependency>
                </dependencies>
                <configuration>
                    <keepDependenciesWithProvidedScope>true</keepDependenciesWithProvidedScope>
                    <createDependencyReducedPom>true</createDependencyReducedPom>
                    <filters>
                        <filter>
                            <artifact>*:*</artifact>
                            <excludes>
                                <exclude>META-INF/*.SF</exclude>
                                <exclude>META-INF/*.DSA</exclude>
                                <exclude>META-INF/*.RSA</exclude>
                            </excludes>
                        </filter>
                    </filters>
                </configuration>
                <executions>
                    <execution>
                        <phase>package</phase>
                        <goals>
                            <goal>shade</goal>
                        </goals>
                        <configuration>
                            <transformers>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.handlers</resource>
                                </transformer>
                                <transformer implementation="org.springframework.boot.maven.PropertiesMergingResourceTransformer">
                                    <resource>META-INF/spring.factories</resource>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.AppendingTransformer">
                                    <resource>META-INF/spring.schemas</resource>
                                </transformer>
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ServicesResourceTransformer" />
                                <transformer implementation="org.apache.maven.plugins.shade.resource.ManifestResourceTransformer">
                                    <mainClass>${start-class}</mainClass>
                                </transformer>
                            </transformers>
                        </configuration>
                    </execution>
                </executions>
            </plugin>
        </plugins>
    </pluginManagement>
  1. Do I need all this plugins? 我需要所有这些插件吗? And a pluginManagement inside a pom without heredity ... unnecessary? 在pom中没有遗传的pluginManagement ...是不必要的吗? What do I need from it? 我需要什么呢?

After finishing the pom.xml I modified the main class and added a second line to it: 完成pom.xml之后,我修改了主类,并在其中添加了第二行:

AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(JpaConfig.class);
ApplicationContext ctx = SpringApplication.run(SpringBootApp.class, args);
  1. There are now two contexts. 现在有两种情况。 It can start, yes, but I am not sure if this is useful. 可以开始,是的,但是我不确定这是否有用。 I do not want to configure everything twice. 我不想两次配置所有内容。 So how can I modify my JpaConfig Class in order to also configure spring boot. 因此,如何修改我的JpaConfig类以配置弹簧启动。 And going on: how can I modify my two lines in my main class in order to make the configuration only once? 并继续:如何只修改一次主类中的两行? Maybe use SpringApplication.run and give it the JpaConfig Class? 也许使用SpringApplication.runSpringApplication.run提供JpaConfig类? But the constructor is not allowing this. 但是构造函数不允许这样做。

  2. When I start this current project with all the modifications, independently that maybe hibernate and/or jpa and/or spring annotations are searched and bild twice, I get this error: 当我以所有修改启动此当前项目时,独立地可能搜索了hibernate和/或jpa和/或spring注释,并两次执行了bild操作,我收到此错误:

    org.springframework.beans.factory.BeanDefinitionStoreException: Failed to process import candidates for configuration class [myProject.dependency.spring.javaOnly.springBoot.SpringBootApp]; org.springframework.beans.factory.BeanDefinitionStoreException:无法处理配置类[myProject.dependency.spring.javaOnly.springBoot.SpringBootApp]的导入候选对象; nested exception is java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. 嵌套异常为java.lang.IllegalArgumentException:在META-INF / spring.factories中找不到自动配置类。 If you are using a custom packaging, make sure that file is correct. 如果您使用的是自定义包装,请确保该文件正确无误。 // ... Caused by: java.lang.IllegalArgumentException: No auto configuration classes found in META-INF/spring.factories. // ...原因:java.lang.IllegalArgumentException:在META-INF / spring.factories中找不到自动配置类。 If you are using a custom packaging, make sure that file is correct. 如果您使用的是自定义包装,请确保该文件正确无误。

I am not quite sure what this is telling me because I created a spring.factories in META-INF and when I compile it, there are even two spring.factories inside the META-INF folder. 我不太确定这会告诉我什么,因为我在META-INF创建了spring.factories ,并且在编译时, META-INF文件夹中甚至还有两个spring.factories The one I created myself and one created by the compiler. 我自己创建的一个,编译器创建的一个。 And regardless of whether I have two or only one spring.factories inside the META-INF folder, the error still is the same. 而且,无论我在META-INF文件夹中是否只有两个spring.factories ,错误仍然是相同的。
But maybe this one will fix itself when the other two questions are solved. 但是也许当其他两个问题解决后,这个问题就会解决。 So thank you so much for your time and patience for this long post and my maybe stupid questions. 因此,非常感谢您的时间和耐心等待这篇漫长的帖子以及我可能很愚蠢的问题。 But I hope you understand that I am still learning and trying my best to improve and these problems are unsolvable for me since a few days. 但是,我希望您了解我仍在学习并尽我最大的努力,而且几天以来这些问题对我来说是无法解决的。 So thanks for any hint or/and help. 因此,感谢您的任何提示或帮助。

My suggestion is integarte your existing spring project to spring boot project as spring boot built with the full spring based infrastructure, especially the auto-configuration. 我的建议是将您现有的spring项目集成到spring boot项目中,因为该spring boot是基于完整的spring基础架构构建的,尤其是自动配置。

And

  1. Only the spring-boot-maven-plugin plugin is need for the standard spring boot project - doc 标准spring boot项目仅需要spring-boot-maven-plugin插件-doc
  2. Do not need AnnotationConfigApplicationContext here, The SpringApplication class provides a convenient way to bootstrap a Spring application that will be started from a main() method. 这里不需要AnnotationConfigApplicationContextSpringApplication类提供了一种便捷的方式来引导将从main()方法启动的Spring应用程序。 In many situations you can just delegate to the static SpringApplication.run method 在许多情况下,您可以只委托给静态SpringApplication.run方法

    ApplicationContext ctx = SpringApplication.run(SpringBootApp.class, args); ApplicationContext ctx = SpringApplication.run(SpringBootApp.class,args);

  3. Spring boot recommend that you locate your main application class ( SpringBootApp ) in a root package above other classes. Spring Boot建议您在其他类之上的根包中找到主应用程序类( SpringBootApp )。 Spring boot will apply the @ComponentScan with the default root package here, so it will load your JpaConfig defaultly, and @ComponentScan(basePackages = {"myProject"}) is not necessary here, but this is dependent on the package definition in your project. 春季启动将在此处应用具有默认根包的@ComponentScan ,因此它将默认加载您的JpaConfig ,这里不需要@ComponentScan(basePackages = {"myProject"}) ,但这取决于您项目中的包定义。
  4. META-INF/spring.factories is used to register all the auto-configuration classes, if you do not need your customized auto-configurtion class, you can delete this file or just level this file empty. META-INF/spring.factories用来注册的所有自动配置类,如果你不需要你的自定义自动configurtion类,你可以删除这个文件或只是水平这个文件是空的。

Good journey. 好走。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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