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.
Related
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.
Currently we have a framework(a customized MVC pattern in flex and command pattern in java) which works well with our use case. we are thinking about migration of our server to spring framework. How advisable it is?. our java framework is also loosely coupled.But I see spring more loosely coupled with some concepts Dependency injection and inversion of control( which i still need to get some idea).Basically in what kind of use-case people use spring.How efficient it is?.if its advisable also please let me know where to start with.
Using a framework like Spring or Guice helps you keep your applications organized and loosely coupled over time. A dependency injection framework essentially extracts object construction away from an application, allowing the application to focus on what it needs to do instead of any architectural concerns.
Another upfront advantage of using dependency injection is that your application no longer worries about object construction, thus allowing you to build mock objects to test each portion of you application independently.
I highly suggest reading Dhanji Prasanna's book Dependency Injection.
One benefit of moving to spring is that new developers you bring on will be more likely to know that tool, and may come up to speed faster.
That being said, rewriting an app needs to require a lot of justification. Is your current architecture failing you for any reason?
We basically need to be able to adjust behaviour at start-up time, by providing desired classes to be produced by various factories inside our application (to avoid the hard binding of the "new" operator).
I am aware that this is provided by several large frameworks, but I was looking for something easily used by a stand-alone Java application without being gigantic.
Any suggestions?
Edit: It is my experience that frameworks tend to grow big as part of maturing (and complex too). I need this to be retrofittable to a legacy application as part of major refactoring (technical debt), so simplicity is essential of the used libraries. I do not mind having to do a bit of coding in our application, but it must be very visible what is going on. AOP has a tendency for moving stuff out of the way, and that may make the application harder to maintain.
Edit: We have now reached the point where we actually need to make a decision. The application will probably live for decades so we need to make a reversible decision with a framework that will be maintained for hopefully as long. I really like the static type check available with Guice, but not that the annotations bind explicitly to Guice instead of being external like in Spring. I also like that code appears to be more concise when using Guice as opposed to Spring. We need something that is robust and helpful. We do not need more than just DI at the moment. Is there a use case that definitive says go for one of these?
Edit 2011-07-27: The final decision was to use the JSR-330 API in code, and choose on a per-project basis if to use Spring, Guice or Weld. For stand-alone applications Guice has worked well so far as the JSR-330 implementation.
You can always use Spring Framework 2.5. It is a big one, but if you planning to use only DI you can use spring-core and spring-beans modules, which are pretty small (ca. 500KB and 300KB).
There is also Google Guice 2.0 which comes with a package with only basic stuff (no AOP) and it's 430KB.
Have you looked at the Google Guice framework? It's pretty lightweight and annotation-based, avoiding XML configuration files
There's also Pico- and Nano-container (from codehaus) which are quite lightweight although the last time I looked (admittedly a few years ago) the documentation was lacking.
I must say that I agree with others about what I assume is your presumption that Spring is massive and confusing. It's really a very simple IoC container and to be recommended.
There are a couple I know of you might find useful:
PicoContainer
Plexus (used in Maven)
I've found Plexus very useful in standalone apps as it has optional utility components for CLI interaction.
By "gigantic" I'm going to assume you're referring to Spring, but that's unfair, since you can cherry-pick the bits of Spring you want to use. If all you need is the IoC container, just use the appropriate JAR files and the appropriate bit of the API, and ignore the rest of it.
Most answers so far seem to be concerned with the size of the jar files to be added.
However I think the more important question is the impact on the project: How many lines of code must be added/changed in order to use the framework?
Even the "big" spring framework is actually very easy to use:
You basically need:
a xml file that describes your factories.
one line of code to initialize the container by loading the xml file
The nice thing is that spring is non-intrusive. So you do not have to implement specific interfaces or add any specific annotations or imports to your classes.
At best the single spot where you actually initialize the Spring container is the only
place in your application that has an actual dependency to spring classes.
I would strongly suggest to take a look at Spring ME. Although originally meant to be a way to use Spring on Java ME applications, it also works fine for standalone applications.
True, it doesn't give you all of the bells and whistles that Spring (Full) has to offer, but then again, Full Spring is much much more than a simple dependency injection framework.
On the plus side: it's based on a (compliant) subset of Spring's configuration files, and the footprint of the runtime is 0%. In fact, there isn't any. Spring ME will take your application context, and turn it into a class that has no dependencies on classes other than your own.
What's wrong with Spring?
These days it's packaged pretty well so you wouldn't need to take the whole kit and caboodle.
As an aside, I'm not a fan of the annotation based injection frameworks. This is because the annotations are bound to the class rather than the instance, the later being a pre-requisite, imho, for DI. This means every instance of a given class gets the same object(s) injected, which seems to defeat the point.
Also consider that DI doesn't even need a framework, what's wrong with your main method wiring together the application?
If you want something maximally simple and appropriate, then write some code that does what you want done. Presumably this involves wiring together factories based partly on fixed logic, and partly on run-time settings.
This has the advantage that the set of possible run-time configurations is known, and so documentable and testable.
It has the disadvantage that an deploying an unanticipated logic change inherently takes an extra second or so of compile time, and (more significantly) can't be sneaked into production without full testing by disguising it as 'just a configuration change'.
About a year ago I asked myself a question very like this. So I spend a few hours reading the Spring and Guice documentation. After about an hour with Spring I was left feeling that I could get a basic web app going, but had no idea how to use it in a stand alone application. After an hour with the Guice document everything had clicked and I could see just how I to do what I wanted to get done.
Now on to recommending Guice? Well no. What does your team already know? If someone already knows say Spring leaver that knowledge and have them spread it about. Like wise with Guice or Pico.
If you want something really light weight you might want to have a look at fuse it's fairly extendable so might be what you're looking for.
cheers
N
I've read about Google Guice, and understand the general issues with other approaches to dependency injection, however I haven't yet seen an example of someone using Guice "in practice" where its value becomes clear.
I'm wondering if anyone is aware of any such examples?
Using Google Guice to provides ease in unit testing is only high-level advantage. Some people might not even use unit testing in their project. People has been using Spring/Dependency Injection more than only for unit testing.
The low level advantage of using Google Guice is a matter of cohesion in your application, your classes in the project can be loosely coupled between each other. I can provide a class for another class without them being dependent to each other.
Consider this example:
public class A {
}
public class B {
A a = new A();
}
Class B would be tightly coupled to Class A, or in other words it is dependent to class A's existence.
But with Guice I can instead make it loosely coupled like this:
public class B {
private A a;
#Inject
public B(A a) {
this.a = a;
}
}
Class B is now loosely coupled to A, and Guice is responsible to provide the instance of A instead of B having to instantiate it. With this you can extend it to provide interface of A to B, and the implementation can be a Mock object if you want to unit test your apps.
Having said that we're only discussing the benefits of Dependency Injection so far. Beyond Dependency Injection, the benefits of using Google Guice is:
Guice has a very clean implementation of constructor Injection. As you can see from the example you just add #Inject annotation constructor.
Guice also has setter Injection using the same annotation.
Having said that, the annotation based Injection is very clean approach compared to XML based injection like some other DI implementation.
All of the dependency injection and configuration is using Java, so you are guaranteed to get a typesafety in your application by default.
Guice has a very lightweight implementation of Aspect Oriented Programming (or maybe you can call it as a wrapper to the AOPAlliance AOP implementation). And the good thing of it is it doesn't generate stubs or what-so-ever.
That's the overview of it. But as you get deeper with Guice, there's so many more good things about it. A simple real life example is if you are using GWT with MVP implementation, the components/widgets in your GWT application are very loosely coupled and not tightly integrated to each other.
Maybe you should go back in time and look closer at the problems Guice wanted to solve. To understand the motivations behind Guice, the Bob Lee: I Don't Get Spring news on TheServerSide.COM (and its comments) is the perfect starting point. Then, go ahead with the announcement of Google Guice, A Java Dependency Injection Framework (and the comments) and the Tech Talk: Bob Lee on Google Guice (and the comments).
Personally, I was sharing concerns about evil XML: XML configuration hell, XML and possible runtime errors, error-prone and refactoring-adverse string identifiers, etc, etc. Actually, I believe that skeptical opinions on Spring and concurrence were good for everybody (including Spring). I was thus happy to see a new player in the DI framework landscape, especially a modern framework leveraging Java 5 features (generics and annotations for the sake of type safety).
And because Google is running Guice in mission critical applications (almost every Java-based application is also a Guice-base application: AdWords, Google Docs, Gmail, and even YouTube as reported by "Crazy" Bob Lee in Guice²), I can't believe Guice is totally wrong and doesn't provide any value. Sadly, I don't think Google will provide much code of these applications as examples... But you may find interesting things in the list of applications that use Guice and/or the list of 3rd party Guice addons. Or check out the books mentioned in Guice². Or ask Bob :)
I think the advantage comes with coding to interfaces, testing, and proxies.
Coding to an interface helps keep your code layered properly, makes it possible to inject mocks for testing, and lets you generate proxies automagically so client code need not worry about implementation.
This is true for Guice, Spring, PicoContainer, and all DI frameworks.
Succinct enough?