How to migrate from traditional java web application (with web.xml) to spring boot? - spring

I wanna switch my projects to spring-based product.
My first step is to transform my java web application from a generated WAR file, to a standalone executable jar, powered by spring boot.
Let's take a open source web application example from github.: Vaadin-Spring Web Application
The web.xml file can be found here.
The root-context file can be found here.
I hope that there are some guides for me to perform the transformation.
I have also submit an issue in the spring-boot project.

This application is not a Spring MVC application as far as I can tell - it would probably be a lot easier to migrate if it was. The goal (per the github issue) is to obtain an executable JAR. The basic plan though might be to migrate first to a WAR using Spring Boot and then to a JAR once that is working. It's a pretty simple app so all we really need to do is look at the web.xml and translate it into the relevant Spring Boot features. Here are some general guides:
Create a deployable WAR by extending SpringBootServletInitializer (e.g. in a class called Application), and add the Spring Boot #EnableAutoConfiguration annotation. Example:
#Configuration
#EnableAutoConfiguration
#ComponentScan
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
Then add some configuration:
A #Bean of type Servlet or ServletRegistrationBean installs that bean in the container as if it was a <servlet/> and <servlet-mapping/> in web.xml
A #Bean of type Filter or FilterRegistrationBean behaves similarly (like a <filter/> and <filter-mapping/>).
The ApplicationContext in this case is rooted in an XML file, so the easiest first step is to #Import that into the Spring Application. This one is so simple that it can be recreated in a few lines as #Bean definitions.
Static resources can be moved to /public (or /static or /resources or /META-INFO/resources) in the classpath root
Once the WAR is working we make it executable by adding a main method to our Application, e.g.
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
See also the Getting Started Guide on Converting a JAR to a WAR.
As I said, the biggest problem with this specific app is that it isn't a Spring MVC app. As the Irishman might say "If I wanted to get to there, sir, I wouldn't be starting from here." This is an interesting question in general, but I recommend anyone else looking to migrate a Spring application to Spring Boot read the general advice here but maybe start another discussion somewhere else.
Anyway, I'll have a bash at converting this specific app (source code jars would be nice), and update this response if I learn anything new.

Related

Vaadin-SpringBootServletInitializer vs AppShellConfigurator .What is valid for production build on external Tomcat?

I'm building my project with Spring Boot and when uploading to Tomcat as a .war it was throwing errors.
In any case what fixed it is to change
public class Application implements AppShellConfigurator {
to
public class Application extends SpringBootServletInitializer implements AppShellConfigurator {
I've used a sampler from start.vaadin.com v22 to build upon which came by default with the
Application implements AppShellConfigurator
Like this it was running fine inside Intellij with the embedded Tomcat but when deploying to a standalone/external one , I had to change that to the latter.
Is that required ? if yes then the docs should be updated because at
https://vaadin.com/docs/v22/flow/production/production-build
there's no mention of it.
As M. Deinum said this is related to Spring Boot.
Usually you run the Spring Boot Application as an executable JAR. But If you want to run it as a WAR inside a Tomcat you have to use SpringBootServletInitializer.
The first step in producing a deployable war file is to provide a
SpringBootServletInitializer subclass and override its configure
method. Doing so makes use of Spring Framework’s servlet 3.0 support
and lets you configure your application when it is launched by the
servlet container. Typically, you should update your application’s
main class to extend SpringBootServletInitializer...
Source: https://docs.spring.io/spring-boot/docs/current/reference/html/howto.html#howto.traditional-deployment

How to integration test auto configuration for a custom Spring Boot style starter library?

I am writing a library to provide some functionality that is shared between multiple different Spring Boot applications that I work with.
I would like to do something similar to the auto-configuration that is provided by the many Spring Boot starter libraries exist. That, or some other simple declarative way to integrate my library with the ApplicationContext of the apps using it.
I have found some resources explaining how auto configuration works. I can figure out the above problem.
However, I have not been able to find any good examples of how I can test as part of my library's test suite that it suitably integrates with a Spring Boot application. Ideally, I would start up a simple Spring Boot app written in the library's test directly just for the sake of testing, add the right annotation to it, and be able to assert that the correct beans are then configured.
I have tried creating a TestApplication class that does that and writing integration tests using the SpringBootTest annotation but the TestApplication was never started before my test started.
What can I do to start up a simple app like that solely for the purpose of testing my library? My tests are written with Spock and Spock-Spring in case that changes things versus other test frameworks.
I was able to make it work with the following test class:
#SpringBootTest
#ContextConfiguration(classes = TestApplication)
class DummyIntegrationSpec extends Specification {
#Autowired
DummyService dummyService
void 'dummy service should exist'() {
expect:
dummyService.getMessage() == DummyConfiguration.MESSAGE
}
}
and this TestApplication class at src/test/groovy/com/example/project/TestApplication.groovy
#SpringBootApplication(scanBasePackages = 'com.example.project.config')
#EnableAutoConfiguration
class TestApplication extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(TestApplication)
}
static void main(String[] args) {
SpringApplication.run(TestApplication, args)
}
}
The two key changes I had to make in order for the TestApplication to start and load the correct context when I moved my TestApplication class from src/main to src/test were:
the TestApplication class needed to be added to the ContextConfiguration annotation
the package that my library's Java config files live in needed to be added to the SpringBootApplication scanBasePackages field
The library auto-configuration does follow a similar structure to the one mentioned in the link tom provided.
Your auto-configuration should be automatically picked while your main spring application/test is starting and all beans will be registered in your context. They will be available for auto-wiring and follow your conditions and init order.
As a summary, make sure you have an auto-configuration annotated by #Configuration class with an #Import that imports your #Configuration annotated configuration classes (inside of them you define beans with methods annotated with #Bean). Also make sure you created a spring.factories file that include your auto-configuration class and that you removed the spring boot maven plugin (for the packaging to be right).
Also, make sure your auto-configuration project is NOT annotated by things like #SpringBootApplication, #EnableAutoConfiguration, #ComponentScan or other spring boot annotations that need to be only in the main spring boot projects (There should be one of them in each stack).
Please also see the article below:
Spring boot is based on a lot of pre-made auto-configuration parent projects. You should already be familiar with spring boot starter projects.
You can easily create your own starter project by doing the following easy steps:
Create some #Configuration classes to define default beans. You should use external properties as much as possible to allow customization and try to use auto-configuration helper annotations like #AutoConfigureBefore, #AutoConfigureAfter, #ConditionalOnBean, #ConditionalOnMissingBean etc. You can find more detailed information on each annotation in the official documentation Condition annotations
Place an auto-configuration file/files that aggregates all of the #Configuration classes.
Create a file named spring.factories and place it in src/main/resources/META-INF.
In spring.factories, set org.springframework.boot.autoconfigure.EnableAutoConfiguration property with comma separated values of your #Configuration classes:
org.springframework.boot.autoconfigure.EnableAutoConfiguration=
com.mycorp.libx.autoconfigure.LibXAutoConfiguration,
com.mycorp.libx.autoconfigure.LibXWebAutoConfiguration
Using this method you can create your own auto-configuration classes that will be picked by spring-boot. Spring-boot automatically scan all maven/gradle dependencies for a spring.factories file, if it finds one, it adds all #Configuration classes specified in it to its auto-configuration process.
Make sure your auto-configuration starter project does not contain spring boot maven plugin because it will package the project as an executable JAR and won't be loaded by the classpath as intended - spring boot will not be able to find your spring.factories and won't load your configuration

Convert a Spring MVC application to Spring Boot - BeanCurrentlyInCreationException issue

I have a Spring MVC application, using Hibernate for my entities persistence management. I am able to build, deploy and run it on some application server such as glashfish or tomcat, all is fine.
Now, I want to convert it into a Spring Boot application. I added the following class:
#SpringBootApplication
public class Application extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
public static void main(String[] args) {
ConfigurableApplicationContext context =
SpringApplication.run(Application.class, args);
}
}
and added the spring-boot, spring-boot-autoconfigure, and spring-boot-starter-tomcat dependencies to my pom.
Alas, when trying to run the application, I get the following error:
BeanCurrentlyInCreationException: Error creating bean with name
'MyClassDAO': Bean with name 'MyClassDAO' has been injected into
other beans [MyOtherClassDAO] in its raw version as part of a circular
reference, but has eventually been wrapped. This means that said other
beans do not use the final version of the bean. This is often the result
of over-eager type matching - consider using 'getBeanNamesOfType' with
the 'allowEagerInit' flag turned off, for example.
I don't know how to use 'getBeanNamesOfType' and set the allowEagerInit off (I do not use XML configuration). Of course, I'm not sure this would solve my issue anyway.
Any ideas on how I can fix this?
If it's really some intilization issue then i believe the you must be having your class in other package and due to some cache issues it doesn't include those classes in class path to scan in container so to do this manually you can put a annotation just below #springbootapllication is #EnableComponentScan("enter the package name of the class which is not initializing") also on that dao class put #service or #component annotation to let the application include then in container

Spring Boot application war in a standalone servlet container

A general question about building a war from a spring boot application and running it in a standalone servlet container. The documentation I've seems seems at odds with examples on Stack Overflow.
The answer here shows the way I read of doing this a couple of months ago. I read this here, but the guide seems to have changed losing the actual example app.
Here the "configure" method references the main spring boot Application.class.
public class WebInitializer extends SpringBootServletInitializer {
#Override
protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
return application.sources(Application.class);
}
}
There are also these posts here and here that show the "configure" method referring to the SpringBootServletInitializer sub class itself.
public class BootStrap extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(BootStrap.class, args);
}
#Override
protected SpringApplicationBuilder configure(
SpringApplicationBuilder application) {
return application.sources(BootStrap.class);
}
}
and also there is a main method.
Also the spring-boot-sample-traditional  example app at https://github.com/spring-projects/spring-boot/tree/master/spring-boot-samples, which shows "WAR packaging"
does it differently
public class WebConfig extends WebMvcConfigurerAdapter {.........
I was wondering is there are issues with choosing over these different ways of seemingly achieving the same thing in spring boot? Or do they all work equally as well and are interchangeable?
Having your main application class extend SpringBootServletInitializer (Bootstrap in your question) or using a separate class (WebInitializer in your question) is down to personal taste. My preference is to take the Bootstrap approach but they both work in the same way; pick which ever you prefer.
If you are only going to deploy your application to a standalone servlet container then you don't need a main method. The main method is used if you want to run the application as an executable war (java -jar my-app.war), or you want to be able to run it directly in your IDE, i.e. without having your IDE deploy it to a servlet container.
spring-boot-sample-traditional illustrates the use of web.xml to Bootstrap a Spring Boot application. Generally speaking, this isn't a recommended approach unless you're stuck on a Servlet 2.5 container. The use of WebMvcConfigurerAdapter has nothing to do with WAR packaging. Take a look at its web.xml to see the relevant pieces of configuration.
Use Spring Initializr
http://start.spring.io/
Choose your project type (Gradle or Maven) and Packaging as war.
Add Web as dependency and Generate the project.
This will bootstrap your app with the "correct" way.

Plugin System in Spring Boot for modular applications

I looking for dynamically loading jar in spring boot after compiling, for example I will put jars in some folder and when spring boot is started, all jars from this folder will be injected into spring boot app. I don't know how can I do this with spring boot, and if You know can help me with this, with some example.
I need this jars to have #Service, #Controller as this will be module (plugin), with adding capabilities to my spring boot app.
Is possible to do this with spring boot, and if it is possible, please provide me with some sample code.
Thanks in advance.
UPDATE:
I found something https://www.youtube.com/watch?v=F-sw2pFdcDw https://code.google.com/p/jspf/
UPDATE 2: I can't get #Controller bean from plugin jar registered in Spring Boot
Have a look at FlexiCore, an open-source framework that brings modularity to spring boot utilizing plugins(jars) loaded at runtime See wizzdi and FlexiCore.
for example FlexiCore allows you to create a project ( compiled into a seperate jar from your main application) that contains a spring bean as follows:
#Component
#Extension
public class HelloWorldService implements ServicePlugin{
public String hello() {
return "Hello World!";
}
}
it will be automatically be loaded once placed inside the designated plugins folder, it basically allows a full support for most(all) of spring boot features , so for example you can add a RestController bean to your jar as well , FlexiCore will automatically load that bean allowing you to call the controller as if it was in your main application jar:
#RestController
#Extension
public class TestEntityController implements Plugin {
private static final String template = "Hello, %s!";
private final AtomicLong counter = new AtomicLong();
#Autowired
private TestEntityService testEntityService;
#PostMapping("/createTestEntity")
public TestEntity createTestEntity(#RequestParam(name="name", required=false, defaultValue="Stranger") String name) {
return testEntityService.createTestEntity(name);
}
#GetMapping("{id}")
public TestEntity getTestEntity(#PathVariable("id")String id) {
return testEntityService.getTestEntity(id);
}
}
Disclaimer: I am the CTO of wizzdi, the company powering FlexiCore.
One option is definitely to just use broad #ComponentScan. If you add new jar to classpath the annotated classes from that jar will get discovered via #ComponentScan, #Controllers will get mapped etc.
The XML equivalent here would be placing xml configuration files somewhere to your classpath (META-INF folder being obvious choice) and import them all using wildcard. The idea is the same. If the plugin jar file is on classpath you will get the xml file imported and the beans (controllers, ...) will get loaded.
There are drawbacks to this approach like the modules not being isolated but its definitely option for simpler applications.
You can find a sample spring boot web project here.
By dynamically loading jars I assume you want to add dependencies to your project. For this you can update pom.xml of the sample project and put your dependencies here.

Resources