I hear a lot about Spring, people are saying all over the web that Spring is a good framework for web development. What exactly is Spring Framework for?
This question is related to
java
spring
frameworks
In the past I thought about Spring framework from purely technical standpoint.
Given some experience of team work and developing enterprise Webapps - I would say that Spring is for faster development of applications (web applications) by decoupling its individual elements (beans). Faster development makes it so popular. Spring allows shifting responsibility of building (wiring up) the application onto the Spring framework. The Spring framework's dependency injection is responsible for connecting/ wiring up individual beans into a working application.
This way developers can be focused more on development of individual components (beans) as soon as interfaces between beans are defined.
Testing of such application is easy - the primary focus is given to individual beans. They can be easily decoupled and mocked, so unit-testing is fast and efficient.
Spring framework defines multiple specialized beans such as @Controller (@Restcontroller), @Repository, @Component to serve web purposes. Spring together with Maven provide a structure that is intuitive to developers. Team work is easy and fast as there is individual elements are kept apart and can be reused.
Spring contains (as Skaffman rightly pointed out) a MVC framework. To explain in short here are my inputs. Spring supports segregation of service layer, web layer and business layer, but what it really does best is "injection" of objects. So to explain that with an example consider the example below:
public interface FourWheel
{
public void drive();
}
public class Sedan implements FourWheel
{
public void drive()
{
//drive gracefully
}
}
public class SUV implements FourWheel
{
public void drive()
{
//Rule the rough terrain
}
}
Now in your code you have a class called RoadTrip as follows
public class RoadTrip
{
private FourWheel myCarForTrip;
}
Now whenever you want a instance of Trip; sometimes you may want a SUV to initialize FourWheel or sometimes you may want Sedan. It really depends what you want based on specific situation.
To solve this problem you'd want to have a Factory Pattern as creational pattern. Where a factory returns the right instance. So eventually you'll end up with lots of glue code just to instantiate objects correctly. Spring does the job of glue code best without that glue code. You declare mappings in XML and it initialized the objects automatically. It also does lot using singleton architecture for instances and that helps in optimized memory usage.
This is also called Inversion Of Control. Other frameworks to do this are Google guice, Pico container etc.
Apart from this, Spring has validation framework, extensive support for DAO layer in collaboration with JDBC, iBatis and Hibernate (and many more). Provides excellent Transactional control over database transactions.
There is lot more to Spring that can be read up in good books like "Pro Spring".
Following URLs may be of help too.
http://static.springframework.org/docs/Spring-MVC-step-by-step/
http://en.wikipedia.org/wiki/Spring_Framework
http://www.theserverside.com/tt/articles/article.tss?l=SpringFramework
The accepted answer doesn't involve the annotations usage since Spring introduced support for various annotations for configuration.
There the another way to wire the classes up alongside using a XML file: the annotations. Let's use the example from the accepted answer and register the bean directly on the class using one of the annotations @Component
, @Service
, @Repository
or @Configuration
:
@Component
public class UserListerDB implements UserLister {
public List<User> getUsers() {
// DB access code here
}
}
This way when the view is created it magically will have a UserLister ready to work.
The above statement is valid with a little bonus of no need of any XML file usage and wiring with another annotation @Autowired
that finds a relevant implementation and inject it in.
@Autowired
private UserLister userLister;
Use the @Bean
annotation on a method used to get the bean implementation to inject.
Very short summarized, I will say that Spring is the "glue" in your application. It's used to integrate different frameworks and your own code.
Spring started off as a fairly simple dependency injection system. Now it is huge and has everything in it (except for the proverbial kitchen sink).
But fear not, it is quite modular so you can use just the pieces you want.
To see where it all began try:
It might be old but it is an excellent book.
For another good book this time exclusively devoted to Spring see:
It also references older versions of Spring but is definitely worth looking at.
The advantage is Dependency Injection (DI). It means outsourcing the task of object creation.Let me explain with an example.
public interface Lunch
{
public void eat();
}
public class Buffet implements Lunch
{
public void eat()
{
// Eat as much as you can
}
}
public class Plated implements Lunch
{
public void eat()
{
// Eat a limited portion
}
}
Now in my code I have a class LunchDecide as follows:
public class LunchDecide {
private Lunch todaysLunch;
public LunchDecide(){
this.todaysLunch = new Buffet(); // choose Buffet -> eat as much as you want
//this.todaysLunch = new Plated(); // choose Plated -> eat a limited portion
}
}
In the above class, depending on our mood, we pick Buffet() or Plated(). However this system is tightly coupled. Every time we need a different type of Object, we need to change the code. In this case, commenting out a line ! Imagine there are 50 different classes used by 50 different people. It would be a hell of a mess. In this case, we need to Decouple the system. Let's rewrite the LunchDecide class.
public class LunchDecide {
private Lunch todaysLunch;
public LunchDecide(Lunch todaysLunch){
this.todaysLunch = todaysLunch
}
}
Notice that instead of creating an object using new keyword we passed the reference to an object of Lunch Type as a parameter to our constructor. Here, object creation is outsourced. This code can be wired either using Xml config file (legacy) or Java Annotations (modern). Either way, the decision on which Type of object would be created would be done there during runtime. An object would be injected by Xml into our code - Our Code is dependent on Xml for that job. Hence, Dependency Injection (DI). DI not only helps in making our system loosely coupled, it simplifies writing of Unit tests since it allows dependencies to be mocked. Last but not the least, DI streamlines Aspect Oriented Programming (AOP) which leads to further decoupling and increase of modularity. Also note that above DI is Constructor Injection. DI can be done by Setter Injection as well - same plain old setter method from encapsulation.
I see two parts to this:
Note that you can perfectly well use Spring in a web application without using Spring MVC. I would say most Java web applications do this, while using other web frameworks like Wicket, Struts, Seam, ...
Spring was dependency injection in the begining, then add king of wrappers for almost everything (wrapper over JPA implementations etc).
Long story ... most parts of Spring preffer XML solutions (XML scripting engine ... brrrr), so for DI I use Guice
Good library, but with growing depnedenciec, for example Spring JDBC (maybe one Java jdbc solution with real names parameters) take from maven 4-5 next.
Using Spring MVC (part of "big spring") for web development ... it is "request based" framework, there is holy war "request vs component" ... up to You
What is Spring for? I will answer that question shortly, but first, let's take another look at the example by victor hugo. It's not a great example because it doesn't justify the need for a new framework.
public class BaseView {
protected UserLister userLister;
public BaseView() {
userLister = new UserListerDB(); // only line of code that needs changing
}
}
public class SomeView extends BaseView {
public SomeView() {
super();
}
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
Done! So now even if you have hundreds or thousands of views, you still just need to change the one line of code, as in the Spring XML approach. But changing a line of code still requires recompiling as opposed to editing XML you say? Well my fussy friend, use Ant and script away!
So what is Spring for? It's for:
Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12
Spring is a good alternative to Enterprise JavaBeans (EJB) technology. It also has web framework and web services framework component.
Old days, Spring was a dependency injection frame work only like (Guice, PicoContainer,...), but nowadays it is a total solution for building your Enterprise Application.
The spring dependency injection, which is, of course, the heart of spring is still there (and you can review other good answers here), but there are more from spring...
Spring now has lots of projects, each with some sub-projects (http://spring.io/projects). When someone speaks about spring, you must find out what spring project he is talking about, is it only spring core, which is known as spring framework, or it is another spring projects.
Some spring projects which is worth too mention are:
If you need some more specify feature for your application, you may find it there too:
There are also some tiny projects there for example spring-social-facebook (http://projects.spring.io/spring-social-facebook/)
You can use spring for web development as it has the Spring MVC
module which is part of Spring Framework project. Or you can use spring with another web framework, like struts2.
Spring is three things.
The problem is that Spring DI is really well thought out, the wrappers around other things are really well thought out in that the other things thought everything out and Spring just nicely wraps it. The Spring implementations of MVC and REST and all the other stuff is not as well done (YMMV, IMHO) but there are exceptions (Spring Security is da bomb). So I tend to use Spring for DI, and its cool wrappers but prefer other stuff for Web (I like Tapestry a lot), REST (Jersey is really robust), etc.
Spring framework is definitely good for web development and to be more specific for restful api services.
It is good for the above because of its dependency injection and integration with other modules like spring security, spring aop, mvc framework, microservices
With in any application, security is most probably a requirement.
If you aim to build a product that needs long maintenance, then you will need the utilize the Aop concept.
If your application has to much traffic thus increasing the load, you need to use the microservices concept.
Spring is giving all these features in one platform. Support with many modules.
Most importantly, spring is open source and an extensible framework,have a hook everywhere to integrate custom code in life cycle.
Spring Data is one project which provides integration with your project.
So spring can fit into almost every requirement.
Spring is great for gluing instances of classes together. You know that your Hibernate classes are always going to need a datasource, Spring wires them together (and has an implementation of the datasource too).
Your data access objects will always need Hibernate access, Spring wires the Hibernate classes into your DAOs for you.
Additionally, Spring basically gives you solid configurations of a bunch of libraries, and in that, gives you guidance in what libs you should use.
Spring is really a great tool. (I wasn't talking about Spring MVC, just the base framework).
What you'd probably want in a web application with Spring -
In addition, Spring is HUGE - so there are a lot of other things you might be interested in using in a web app such as Spring AOP or Spring Security. But the four things listed above describe the common components of Spring that are used in a web app.
Source: Stackoverflow.com