I think my understanding of spring beans is a bit off.
I was working on my project and I was thinking about this situation.
Say I have class Foo
class Foo(){
public void doSomething(Object a , Object b){ // input parameters does not matter actually.
//do something
}
}
If I am using this class in another class like :
class Scheduler{
....
#Autowired
private Foo foo;
someMethod(){
foo.doSomeThind(a,b);
}
....
}
In the above case Instead of Autowiring the Foo, I can make doSomeThing static and directly use Foo.doSomeThing(a,b)
I was just wondering if there any advantage of creating a bean or if there any disadvantage of using static methods like this?
If they are same, When should I go for spring bean and when should do I simply use a static method?
Static methods are ok for small utility functions. The limitation of static code is that you can't change it's behavior without changing code itself.
Spring, on the other hand, gives you flexibility.
IoC. Your classes don't know about the exact implementation of their dependencies, they just rely on the API defined by interface. All connections are specified in configuration, that can be different for production/test/other.
Power of metaprogramming. You can change the behavior of your methods by merely marking them (via annotations of in xml). Thus, you can wrap method in transactions, make it asynchronous or scheduled, add custom AOP interceptors, etc.
Spring can instrument your POJO method to make it an endpoint to remote web service/RPC.
http://docs.spring.io/spring-framework/docs/current/spring-framework-reference/html/
Methods in Spring beans can benefit from dependency injection whereas static methods cannot. So, an ideal candidate for static method is the one that does things more or less independently and is not envisioned to ever need any other dependency (say a DAO or Service)
People use Spring not because of some narrow specific futures that cannot be replaced by static classes or DI or whatever. People use Spring because of a more abstracted features and ideas it provide out of the box.
Here is a nice quote from Someone`s blog:
Following are some of the major benefits offered by the Spring Framework:
Spring Enables POJO Programming. Spring enables programmers to develop enterprise-class applications using POJOs. With Spring, you are able to choose your own services and persistence framework. You program in POJOs and add enterprise services to them with configuration files. You build your program out of POJOs and configure it, and the rest is hidden from you.
Spring Provides Better Leverage. With Spring, more work can be done with each line of code. You code in a more fast way, and maintain less. There’s no transaction processing. Spring allows you to build configuration code to handle that. You don’t have to close the session to manage resources. You don’t have to do configuration on your own. Besides you are free to manage the exceptions at the most appropriate place not facing the necessity of managing them at this level as the exceptions are unchecked.
Dependency Injection Helps Testability. Spring greatly improves your testability through a design pattern called Dependency Injection (DI). DI lets you code a production dependency and a test dependency. Testing of a Spring based application is easy because all the related environment and dependent code is moved into the framework.
Inversion of Control Simplifies JDBC. JDBC applications are quite verbose and time-taking. What may help is a good abstraction layer. With Spring you can customize a default JDBC method with a query and an anonymous inner class to lessen much of the hard work.
Spring’s coherence. Spring is a combination of ideas into a coherent whole, along with an overall architectural vision to facilitate effective use, so it is much better to use Spring than create your own equivalent solution.
Basis on existing technologies. The spring framework is based on existing technologies like logging framework, ORM framework, Java EE, JDK timers, Quartz and other view related technologies.
During unit testing you have more flexibility using bean because you can easily mock your bean methods. However, that is not the same with static methods where you may have to resort to PowerMock (which I recommend you stay away from if you can).
It actually depends on the role of the component you are referring to: Is this feature:
An internal tooling: you can use static (you wouldn't wrap Math.abs or String.trim in a bean)
Or a module of the project: design it to be a bean/module-class (a DAO class is best modular to be able to change/mock it easily)
Globally, you should decide w.r.t your project design what are beans and what are not. I think many dev put too much stuff inside bean by default and forget that every bean is an public api that will be more difficult to maintain when refactoring (i.e. restrained visibility is a good thing).
In general, there are already several answers describing the advantages of using spring beans, so I won't develop on that. And also note that you don't need spring to use bean/module design. Then here are the main reasons not to use it:
type-safety: Spring bean are connected "only" at runtime. Not using it, you (can) get much more guaranties at compile time
It can be easier to track your code as there is no indirection due to IoC
You don't need the additional spring dependency/ies which get quite heavy
Obviously, the (3) is correct only if you don't use spring at all in your project/lib.
Also, The (1) and (2) really depend on how you code. And the most important is to have and maintain a clean, readable code. Spring provides a framework that forces you to follow some standard that many people like. I personally don't because of (1) and (2), but I have seen that in heterogeneous dev teams it is better to use it than nothing. So, if not using spring, you have to follow some strong coding guidelines.
I'm comfortable programming in Java, but am fairly new to Spring. I've been reading about dependency-injection/inversion of control (and using it with Spring for the past few months), but I can't figure out the need for a separate language (xml/spring) to accomplish it.
What is wrong with creating a singleton in Java called DependencyHandler, and keeping everything in the same language? What are the advantages I get by using xml/Spring?
Dependency Injection does not require a separate language.
Spring is a framework for Java that historically required configuration in xml. Now you can configure it using xml, or java annotations.
Google's Guice is a simple dependency injection framework that has all configuration in Java.
There can be legitimate reasons why a custom language (in xml) can be better than Java for a specific purpose. For DI though, the reasons are stretchy, and in fact, not the real reasons.
From countless testimonies from happy Spring users, the overwhelming reason is that they somehow think xml is not code. They are so tired of writing boilerplate Java code, they are happy to switch to boilerplate xml. And that makes them happy.
Human beings are not rational when it comes to economic matters. We have elaborate systems that transfer resources in circles, finding comfort and security in such pointless waste of efforts.
But I guess happiness is the most important thing, however retarded it could be.
You can make dependency injection frameworks that use Java syntax, too. Just look at Google Guice, for example.
I'll answer the "benefits" part for XML specifically, although there aren't many.
Having configuration completely separate from code removes all framework artifacts from the source, which can be beneficial.
It's easier (not ridiculously so, but enough to be noteworthy) to create toolchains that affect configuration files: property loading/replacement, config-aware GUI config editors, documentation generation, etc.
Centralized configuration; instead of config being strewn around the codebase, it's in a group of files (or single file). This isn't an XML-only vitrue, it depends on how things are configured.
I think some types of configuration lend themselves to external configuration more than others. I choose based on what seems appropriate given the reqs, what the framework allows, and how the framework handles config aspects.
Spring is just an easy way to manage dependency injection in large projects.
But you can inject dependencies by using a static factory method on your class:
public class Foo
{
public Foo static mkFoo(/* dependencies */)
{
// assign dependencies to members
}
// ordinary class stuff
}
Then you just do Foo.mkFoo(/*dependencies*/) whenever you want a Foo. No spring required.
What is wrong with creating a singleton in Java called DependencyHandler, and keeping everything in the same language?
Handling all your dependencies in a single class is going to get messy quickly, and will result in coupling with all of your other classes. But that isn't a reason to not handle DI in plain java.
I've recently studied about Guice in a University course, and have seen the Google I/O video about it. In the video, they claim to use it in every Google project, including Wave, etc. I was wondering - is Guice really that ubiquitous? Is it really a must-know-must-use for programmers in Java? Should I always use it over a factory?
Thanks
Guice is a dependency injection framework. When using Java, you should definitely considering dependency injection framework (DI). DI can save you a lot of boiler plate code for (web)security/authentication, transaction management, logging, databaseaccess, and results in cleaner code.
Alternatively you could consider Spring. Guice is, or at least was easier to use as it didn't rely on XML so much, but Spring has caught up since the latest version (using annotations, javaconfig, etc.).
Well, either way, use a DI framework over you're own factory code, transaction boiler plate code (transaction.start . commit, finally .. etc.), singletons (like static getInstance methods), etc.
is Guice really that ubiquitous? Is it really a must-know-must-use for programmers in Java?
Outside of Google - no, not really. I'm not saying it's not a good product, it just doesn't seem very widely used right now. There are other, more established frameworks out there that provide dependency injection, like Spring or EJB. The main difference is that Guice only does dependency injection.
Should I always use it over a factory?
Of course not. Dependency injection is a useful pattern, but as with all useful tools, there's a right and a wrong time to use it.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
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 in a nutshell? Why should I used it over just plain Java.
Basically Spring is a framework for dependency-injection which is a pattern that allows building very decoupled systems.
The problem
For example, suppose you need to list the users of the system and thus declare an interface called UserLister:
public interface UserLister {
List<User> getUsers();
}
And maybe an implementation accessing a database to get all the users:
public class UserListerDB implements UserLister {
public List<User> getUsers() {
// DB access code here
}
}
In your view you'll need to access an instance (just an example, remember):
public class SomeView {
private UserLister userLister;
public void render() {
List<User> users = userLister.getUsers();
view.render(users);
}
}
Note that the code above hasn't initialized the variable userLister. What should we do? If I explicitly instantiate the object like this:
UserLister userLister = new UserListerDB();
...I'd couple the view with my implementation of the class that access the DB. What if I want to switch from the DB implementation to another that gets the user list from a comma-separated file (remember, it's an example)? In that case, I would go to my code again and change the above line to:
UserLister userLister = new UserListerCommaSeparatedFile();
This has no problem with a small program like this but... What happens in a program that has hundreds of views and a similar number of business classes? The maintenance becomes a nightmare!
Spring (Dependency Injection) approach
What Spring does is to wire the classes up by using an XML file or annotations, this way all the objects are instantiated and initialized by Spring and injected in the right places (Servlets, Web Frameworks, Business classes, DAOs, etc, etc, etc...).
Going back to the example in Spring we just need to have a setter for the userLister field and have either an XML file like this:
<bean id="userLister" class="UserListerDB" />
<bean class="SomeView">
<property name="userLister" ref="userLister" />
</bean>
or more simply annotate the filed in our view class with #Inject:
#Inject
private UserLister userLister;
This way when the view is created it magically will have a UserLister ready to work.
List<User> users = userLister.getUsers(); // This will actually work
// without adding any line of code
It is great! Isn't it?
What if you want to use another implementation of your UserLister interface? Just change the XML.
What if don't have a UserLister implementation ready? Program a temporal mock implementation of UserLister and ease the development of the view.
What if I don't want to use Spring anymore? Just don't use it! Your application isn't coupled to it. Inversion of Control states: "The application controls the framework, not the framework controls the application".
There are some other options for Dependency Injection around there, what in my opinion has made Spring so famous besides its simplicity, elegance and stability is that the guys of SpringSource have programmed many many POJOs that help to integrate Spring with many other common frameworks without being intrusive in your application. Also, Spring has several good subprojects like Spring MVC, Spring WebFlow, Spring Security and again a loooong list of etceteras.
Anyway, I encourage you to read Martin Fowler's article about Dependency Injection and Inversion of Control because he does it better than me. After understanding the basics take a look at Spring Documentation, in my opinion, it is used to be the best Spring book ever.
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
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:
Spring Security - http://projects.spring.io/spring-security/
Spring Webservices - http://projects.spring.io/spring-ws/
Spring Integration - http://projects.spring.io/spring-integration/
If you need some more specify feature for your application, you may find it there too:
Spring Batch batch framework designed to enable the development of
batch application
Spring HATEOAS easy creation of REST API based on HATEOAS principal
Spring Mobile and Spring Andriod for mobile application development
Spring Shell builds a full-featured shell ( aka command line) application
Spring Cloud and Spring Cloud Data Flow for cloud applications
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.
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:
Blind developers who follow the herd
Employers who do not ever want to hire graduate programmers because they don't teach such frameworks at Uni
Projects that started off with a bad design and need patchwork (as shown by victor hugo's example)
Further reading: http://discuss.joelonsoftware.com/?joel.3.219431.12
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 is three things.
Spring handles Dependency Injection and I recommend you read Martin Fowler's excellent introduction on dependency injection.
The second thing Spring does is wrap excellent Java libraries in a very elegant way to use in your applications. For a good example see how Spring wraps Task Executors and Quartz Scheduler.
Thirdly Spring provides a bunch of implementations of web stuff like REST, an MVC web framework and more. They figure since you are using Spring for the first two, maybe you can just use it for everything your web app needs.
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.
What you'd probably want in a web application with Spring -
Spring MVC, which with 2.5+ allows you to use POJOs as Controller classes, meaning you don't have to extend from any particular framework (as in Struts or Spring pre-2.5). Controller classes are also dead simple to test thanks in part to dependency injection
Spring integration with Hibernate, which does a good job of simplifying work with that ORM solution (for most cases)
Using Spring for a web app enables you to use your Domain Objects at all levels of the application - the same classes that are mapped using Hibernate are the classes you use as "form beans." By nature, this will lead to a more robust domain model, in part because it's going to cut down on the number of classes.
Spring form tags make it easier to create forms without much hassle.
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.
I see two parts to this:
"What exactly is Spring for" -> see the accepted answer by victor hugo.
"[...] Spring is [a] good framework for web development" -> people saying this are talking about Spring MVC. Spring MVC is one of the many parts of Spring, and is a web framework making use of the general features of Spring, like dependency injection. It's a pretty generic framework in that it is very configurable: you can use different db layers (Hibernate, iBatis, plain JDBC), different view layers (JSP, Velocity, Freemarker...)
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 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).
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.
The accepted answer doesn't involve the annotations usage since Spring introduced support for various annotations for configuration.
Spring annotations approach (Dependency Injection)
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.
Spring is a lightweight and flexible framework compare to J2EE.
Spring container act as a inversion of control.
Spring uses AOP i.e. proxies and Singleton, Factory and Template Method Design patterns.
Tiered architectures: Separation of concerns and Reusable layers and Easy maintenance.
Spring is a good alternative to Enterprise JavaBeans (EJB) technology. It also has web framework and web services framework component.
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:
http://www.amazon.com/Expert-One-Design-Development-Programmer/dp/0764543857/ref=sr_1_1?ie=UTF8&s=books&qid=1246374863&sr=1-1
It might be old but it is an excellent book.
For another good book this time exclusively devoted to Spring see:
http://www.amazon.com/Professional-Java-Development-Spring-Framework/dp/0764574833/ref=sr_1_2?ie=UTF8&s=books&qid=1246374863&sr=1-2
It also references older versions of Spring but is definitely worth looking at.
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
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 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.