Accessing google Guice based services in spring boot application - spring-boot

I have services developed using Google guice DI framework and I want to inject them in spring boot application. Could anybody thro some light on how we can access the google guice based services in spring boot application? Any pointers to any sample code?

Welcome to StackOverflow!
There are two different things that you could do, depending on what you actually did in the Guice services.
If you used only JSR330 annotations, then you could theoretically simply replace Guice Modules with Spring #Configuration classes and just use Spring to do the D.I. This would work because both Spring and Guice support the JSR330 annotations. In my view, this can work in only fairly simple cases.
Use the org.springframework.guice:spring-guice library from Spring. It allows you to use Guice Modules and the provided beans.
First you need to include it in your pom:
<dependency>
<groupId>org.springframework.guice</groupId>
<artifactId>spring-guice</artifactId>
<version>1.1.3.RELEASE</version>
</dependency>
Then you must configure Spring to use the needed Guice Modules:
#Configuration
#EnableGuiceModules
public static class GuiceConfig {
#Bean
public MyModule myModule() {
return new MyModule();
}
}
You can read more on the GitHub for this project: https://github.com/spring-projects/spring-guice#using-existing-guice-modules-in-a-spring-applicationcontext.

Related

What's the difference between Spring Boot's #Configuration and #AutoConfiguration?

And most important, what's the reason behind the "Auto" prefix? Classes annotated with #Configuration rather than #AutoConfiguration are less automatic or something?
#Configuration is a spring framework annotation and not strictly bound to spring-boot. It was introduced when spring started to allow programmatic creation of spring-beans as to move forward from xml definitions of beans.
#AutoConfiguration is a spring-boot specific annotation not commonly available in spring framework. The reason it exists, is for external providers that cooperate with spring-boot to be able to mark some classes in some libraries they provide with this annotation as to inform spring-boot that those classes could be parsed and make some initializations during start up of spring application automatically.
So if some regular programmer that develops some application happens to have kafka in dependencies then some beans will automatically be created and added in application context and will be ready for the programmer to use, although he has not defined any configuration for them. Spring-boot already knows this as the kafka provider has already informed by marking some class in the jar they provide with the annotation #AutoConfiguration.
For this reason #AutoConfiguration has some more powerful configurations available as before, after, beforeName, afterName as to allow the provider to specify when the configuration is applied during application startup if some order is necessary.
So this annotation is not to be used from some regular programmer that develops an application using spring-boot. It is for someone that develops a library that other users might use with spring-boot. One such example is kafka library.
For this to work in a spring-boot project #EnableAutoConfiguration is needed as well, to enable auto configuration.
From spring documentation
Spring Boot auto-configuration attempts to automatically configure
your Spring application based on the jar dependencies that you have
added. For example, if HSQLDB is on your classpath, and you have not
manually configured any database connection beans, then Spring Boot
auto-configures an in-memory database.
#Configuration instead is to be used from some regular programmer that develops an application using spring-boot or spring-framework as to inform the framework for which beans should be created and how.
#AutoConfiguration was introduced in 2.7 with the idea to mark all auto-configurations with its dedicated annotation and move away from spring.factories for auto-configuration imports in 3.0 as described in Github issue.
According to Spring documentation:
[#AutoConfiguration] indicates that a class provides configuration that can be
automatically applied by Spring Boot. Auto-configuration classes are
regular #Configuration with the exception that
Configuration#proxyBeanMethods() proxyBeanMethods is always false.
Usually, #AutoConfiguration classes automatically configure an application based on the dependencies that are present on the classpath. Those classes are generally marked as #ConditionalOnClass and #ConditionalOnMissingBean annotations that detect the presence or absence of specific classes.
Additionally, if a configuration needs to be applied in a specific order, you can use the before, beforeName, after, and afterName attributes on the #AutoConfiguration, unlike #Configuration which doesn't provide those attributes.

Would #WebService annotation interfere with #Endpoint in Spring Web Services?

I'm writing a Spring Boot Web Services application, thus I'm using #Endpoint and #PayloadRoot annotations.
For documentation purposes I'm using Enunciate, which doesn't support Spring-WS annotatinos at the time of writing.
Would it do any harm if I add the javax.jws.WebService to an already #Endpoint-annotated class too? Should I use only one of them?
As long as you don't have a JAX-WS implementation like CXF in your classpath and configured the WebService annotation will not be considered.

Migrating an existing spring jersey servlet2.5, Jersey2.3 webapp to springboot

Evaluating to port an existing mid to large sized multi module JEE application, this consists servlet 2.5, Jersey for rest and Spring 3.2.9 (JDK8, Maven 3. currently we build a war file and deploy it on to aws. My objective for this exercise is to be able to use spring-boot to create a self contained executable jar that can be installed on AWS and this would help us just run on cloud with java -jar
Is it possible to use spring boot considering the project is not using spring-web module, it is more traditional Servlet2.5 statically declaring all servlets and filters in web.xml
which approach is better, adding spring boot as a parent or dependency.
Any experience and info our senior spring community members have in this kind of migration.
This is absolutely possible to do even if you're not using Spring Web MVC.
You can use spring-boot-starter-parent like a BOM POM, so you can import its dependencies without having to change your POM's parent.
Take a look at the Spring Boot documentation for migrating a web.xml application to Spring Boot. The main points here for traditionally deployed servlets and filters are:
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/>.

Minimum version of spring for spring-boot v 1.3

I have an existing spring application built using spring framework version 3.1.2. I am trying to create a spring-boot application out of this existing application, but getting some dependency issues. So just wondering, what is the spring framework version, that is supported by spring-boot v 1.3.0.
Or to put it in another words, is it possible to have a spring-boot application from a spring 3.1.2 based application?
Spring boot has hard dependencies on classes in Spring 4 and could not be configured to work with Spring 3. If you are really interested in using Spring Boot the only way you can do this is to follow a migration path to Spring 4 and then add Spring Boot to your application.
It is worth mentioning that the "boot" in Spring Boot is meant to be short for bootstrapping, as in initial setup of an application. I'm not saying there would be zero benefits from migrating from Spring 4 vanilla to Spring Boot. But make sure you are migrating for the right reasons the main purpose of Spring Boot is easy bootstrapping of applications but here are some other features which might be worth making the move.
Spring Boot dev-tools (Auto restart on code changes)
Awesome spring boot plugins for maven and gradle to ease upgrading spring in the future (hint it upgrades many other dependencies for you)
Bootstrapping new features such as MongoDb through auto-configuration.
Migration from 3.1 to 3.2
https://docs.spring.io/spring/docs/3.2.x/spring-framework-reference/html/migration-3.2.html
Migration from Spring 3 to Spring 4.
https://spring.io/blog/2014/01/30/migrating-from-spring-framework-3-2-to-4-0-1
There are many features in spring boot that are dependent upon new features added to Spring 4. One primary example is the new list of annotations added to Spring 4 that allow conditional wiring/loading of beans. Which is the primary method of wiring configurations in a plugin-like way.
For example lets see the AutoConfiguration class for the H2 console
https://github.com/spring-projects/spring-boot/blob/master/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/h2/H2ConsoleAutoConfiguration.java
The first thing we see is it's wired to be a Configuration class. It will only load if WebServlet.class is on the classpath and if the property spring.h2.console is = true. It is also configured to load SecurityAutoConfiguration first as this is a dependency at least for securing the h2 console page.
#Configuration
#ConditionalOnWebApplication
#ConditionalOnClass(WebServlet.class)
#ConditionalOnProperty(prefix = "spring.h2.console", name = "enabled", havingValue = "true", matchIfMissing = false)
#EnableConfigurationProperties(H2ConsoleProperties.class)
#AutoConfigureAfter(SecurityAutoConfiguration.class)
public class H2ConsoleAutoConfiguration {
When this Configuration is loaded it will check these conditions and upon all conditions being true then and only then will it load in the beans defined in the class. In this case it wires the h2console servlet.
#Bean
public ServletRegistrationBean h2Console() {
String path = this.properties.getPath();
String urlMapping = (path.endsWith("/") ? path + "*" : path + "/*");
return new ServletRegistrationBean(new WebServlet(), urlMapping);
}
There is also the security configuration in that class which introduces one more concept of conditionally loading a configuration based on another class being loaded into the context. These annotations do not always need to be on a Configuration level but can also apply to the bean level.
These concepts are core to how Spring Boot is implemented and therefore could not work with Spring 3.
Spring 3 list of annotations
http://docs.spring.io/spring/docs/3.0.x/javadoc-api/org/springframework/context/annotation/
Spring 4 Conditional Annotations
https://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/context/annotation/
Thanks Zergleb for posting detailed answer. I found a way to run the spring 3 app as an independent jar by created an uber jar with a little instrumentation to bootstrap spring through a java class.
It is explained nicely in a short post at https://mihhaillapushkin.wordpress.com/2013/02/18/spring-3-for-standalone-applications

Difference between Spring and Spring Boot

There are many people who advised me to use Spring Boot instead of Spring to develop REST web services.
I want to know what exactly the difference between the two is?
In short
Spring Boot reduces the need to write a lot of configuration and boilerplate code.
It has an opinionated view on Spring Platform and third-party libraries so you can get started with minimum effort.
Easy to create standalone applications with embedded Tomcat/Jetty/Undertow.
Provides metrics, health checks, and externalized configuration.
You can read more here http://projects.spring.io/spring-boot/
Unfortunately and I mean this out of personal frustration with Spring boot, I have yet to see any real quantified list, where the differences are explicitly outlined.
There is only qualifications such as the rubbish sentence "...opinionated view..." which are bandied about.
What is clear, is that SpringBoot has wrapped up groups of Spring annotations into its own set of annotations, implicitly.
Further obfuscating, and making the need for anyone starting out in SpringBoot to have to commit to memory what a particular SpringBoot annotation represents.
My reply therefore is of no quantifiable benefit to the original question, which is analogous to that of the SpringBoot authors.
Those behind Spring IMO deliberately set-out to obfuscate, which reflects the obtuseness of their JavaDoc and API's (see SpringBatch API's as an example, if you think I am flaming) that makes one wonder the value of their open-source ethos.
My quest for figuring out SpringBoot continues.
Update. 22-08-2022
Read this (https://docs.spring.io/spring-boot/docs/current/reference/html/using.html#using.auto-configuration) and you will figure out for yourself what "opinionated" means.
There are over 140 Config classes that Springboot can use for this opinionated view, depending on what is on your classpath.
yes, on your classpath.
Finally and bizzarely, the annotation #SpringBootApplication is a configuration annotation as it includes it.
Go figure :=)
Basically, Spring Boot is an opinionated instance of a Spring application.
Spring Boot is a rapid application development platform. It uses various components of Spring, but has additional niceties like the ability to package your application as a runnable jar, which includes an embedded tomcat (or jetty) server. Additionally, Spring Boot contains a LOT of auto-configuration for you (the opinionated part), where it will pick and choose what to create based on what classes/beans are available or missing.
I would echo their sentiment that if you are going to use Spring I can't think of any reasons to do it without Spring Boot.
Spring Boot is opinionated view of Spring Framework projects.Let's analyse it through one program taken from Spring Boot Documentation.
#RestController
#EnableAutoConfiguration
public class Example {
#RequestMapping("/")
String home() {
return "Hello World!";
}
public static void main(String[] args) throws Exception {
SpringApplication.run(Example.class, args);
}
}
It's a very basic REST API and you need to add Spring-boot-starter-web in your POM.xml for the same. Since you have added starter-web dependency, the annotation
#EnableAutoConfiguration guesses that you want to develop a web application and sets up Spring accordingly.
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added. For example, if HSQLDB is on your classpath, and you have not manually configured any database connection beans, then Spring Boot auto-configures an in-memory database.
It's opinionated like maven. Maven creates a project structure for you which it thinks is the general pattern of projects like it adds src/main/java folder or resource folder for you.
Spring boot helps in faster development. It has many starter projects that helps you get going quite faster. It also includes many non functional features like: embedded servers, security, metrics, health checks etc. In short, it makes, spring based application development easier with minimally invading code(Less configuration files, less no of annotations).
Reference: https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#boot-documentation-about
For developing common Spring applications or starting to learn Spring, I think using Spring Boot would be recommended. It considerably eases the job, is production ready and is rapidly being widely adopted.
Spring Boot is supposedly opinionated, i.e. it heavily advocates a certain style of rapid development, but it is designed well enough to accommodate exceptions to the rule, if you will. In short, it is a convention over configuration methodology that is willing to understand your need to break convention when warranted
For Spring Framework, you need to configure your project using XML configuration or Java configuration.
But for Spring Boot, these are preconfigured according to Spring team's view for rapid development. That is why Spring Boot is said to be an "opinionated view" of Spring Framework. It follows Convention over Configuration design paradigm.
Note: These configurations include view resolvers for MVC, transaction managers, way of locating container managed beans (Spring beans) and many more. And of course you can override any of these preconfigurations according to your need.
Spring Boot supports embedded servlet containers like Tomcat, Jetty or Undertow to create standalone applications, which Spring Framework doesn't.
Spring eliminate boilerplate code.
Spring-boot eliminates boilerplate configurations.
more

Resources