Bootstrapping and Configuring Spring. Difference between Configuring ApplicationContext in JavaSE and JavaEE - spring

I am learning Spring framework, and getting an application context is really hard to understand for me. I understand that Bootstrapping Spring in JavaEE and JavaSE is different. I have bootstrapped my application using XML. Now I am not sure how and where to get the application context. I have done it in Servlet's config method for now. The problem with that is, I can't access that context outside of config. I really need some education on this ApplicationContext topic. Is it right to assume that ApplicationContext is a handle by which we can access beans in xml file from Java Code?
Thanks.

Related

Migrating Spring web application to Spring Boot

I have a web project, and I depoly it on tomcat easily. Infact I have a WebAppInitializer class that implements WebApplicationInitializer (this class it's really fat), as you know every application server that supports servlet 3.0, it can easily detect it and try to boot it. Now I wonder that it could be possible to use spring boot starter and without any further configuration, I pass my WebAppInitializer to it and spring boot based on my WebAppInitializer boots my project?
I just want to use the approach of spring-boot to deploy application on Tomcat and I don't want to use other spring-boot's facilities.
Yes, it's an old question. But I do not see an accepted answer and the one closest to a working one only has a link to an external resource. So here it is.
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#boot-features-embedded-container-context-initializer
28.4.2 Servlet Context Initialization
Embedded servlet containers do not directly execute the Servlet 3.0+
javax.servlet.ServletContainerInitializer interface or Spring’s
org.springframework.web.WebApplicationInitializer interface. This is
an intentional design decision intended to reduce the risk that third
party libraries designed to run inside a war may break Spring Boot
applications.
If you need to perform servlet context initialization in a Spring Boot
application, you should register a bean that implements the
org.springframework.boot.web.servlet.ServletContextInitializer
interface. The single onStartup method provides access to the
ServletContext and, if necessary, can easily be used as an adapter to
an existing WebApplicationInitializer.
Scanning for Servlets, Filters, and listeners
When using an embedded
container, automatic registration of classes annotated with
#WebServlet, #WebFilter, and #WebListener can be enabled by using
#ServletComponentScan.
[Tip] #ServletComponentScan has no effect in a standalone container,
where the container’s built-in discovery mechanisms are used instead.
I've tried it. It works
In my use case I have project containing a few dozens of webapps, designed to run on Tomcat as WAR. Lots of logics was neatly crafted into WebApplicationInitializers and it seemed there should be an easier way to reuse all this. Adding implements ServletContextInitializer to those initializers and exposing them as beans through #Configuration classes lit my webservers up with SpringBoot's embedded Tomcat.
http://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-create-a-deployable-war-file describes precisely how to do it
From the Spring Boot docs:
Servlet 3.0+ applications might translate pretty easily if they already use the Spring Servlet 3.0+ initializer support classes. Normally all the code from an existing WebApplicationInitializer can be moved into a SpringBootServletInitializer. If your existing application has more than one ApplicationContext (e.g. if it uses AbstractDispatcherServletInitializer) then you might be able to squash all your context sources into a single SpringApplication. The main complication you might encounter is if that doesn’t work and you need to maintain the context hierarchy. See the entry on building a hierarchy for examples. An existing parent context that contains web-specific features will usually need to be broken up so that all the ServletContextAware components are in the child context.
So yes, it's possible but you need to convert it to SpringBootServletInitializer, which seems to be quite similar.

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

Does Spring Framework come with its own beans?

This text is from the book called Core Java Server Faces:
It is a historical accident that there are two separate mechanisms,
CDI beans and JSF managed beans, for beans that can be used in JSF
pages. We suggest that you use CDI beans unless your application must
work on a plain servlet runner such as Tomcat. The source code for the
book comes in two versions, one with CDI beans (for Java EE 6
application servers) and one with JSF managed beans (for servlet
runners without CDI support).
My question is:
If I use the Spring Framework, and a Tomcat Server, will I need to use one of the beans mentioned above, or does Spring Framework come with its own bean implementations?
As far as I know, Spring Framework supports Dependency Injection. Does it support it if I run the application on Tomcat? Does it mean that I will be using neither the CDI beans nor the JSF Managed means mentioned in this book?
Thank you.
talking about container is more correct than bean implementation. Yes Spring comes with its own container. In fact you can see spring frameworks as a kind of alternative to the full Java EE stack.
Using Spring DI and CDI together has about no interest but you still can use JSF with spring on tomcat although if i would advise you to switch to a Java EE 6 web profile server instead of spring in this case.
Spring comes with is own view framework implementation named spring mvc.
All of this can run perfectly on any servlet container (jetty tomcat etc...) on condition that you provide associated dependencies ofc.

Spring bean not injected in CXF Restful Service on JBoss6

I am writing a CXF Restful service with Spring on JBoss 6. The Spring bean is not injected. Instead of showing gobs of code here, I have shared a sample project here. My understanding is that the spring context is not creating the rest service class and hence the spring bean (CoreService in the project) is not injected. However the same works well in TomCat. I want to get it working on JBoss6.
Please share your thoughts and help me resolve the issue. Your help highly appreciated. Thanks.

can spring inject EJBs into annotated fields of servlet in a Java SE webapp?

Spring has support for injecting javax.ejb.EJB annotations, much like it injects #Autowired and other jsr-220 injection annotations, thanks to the CommonAnnotationBeanPostProcessor class.
However, injection doesn't work for servlets, since the servlet isn't created by spring.
This article - Spring injects servlets too - doesn't give an example using servlets, but claims it's possible using compile-time weaving of aspects. Unfortunately, compile-time weaving is not an option for us. Is it possible to do this at runtime? It's ok to introduce a subclass to the servlet if that helps, but I want to keep EJB annotations so the servlets can still deployed in a Java EE container.
EDIT: The app will be deployed to a Java EE container in production, but I was thinking of using spring for running functional tests and for local deployment for development to take advantage of hot JSP loading in Tomcat.
You will need Java EE container like in Glassfish that supports injection of EJBs and beware that injection works on managed classes like servlets, managed beans..etc (classes that are managed by containers) so ejb injection in normal classes would require you to use lookups instead.

Resources