What exactly is Spring Framework for? [closed] - java

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.

Related

What is main purpose of interface for Service and DAO in spring framework?

I am new for spring framework. I have searched many website for spring mvc on google and i have noticed that created interface for every service and dao but i have some queries as below :
1) What is the main purpose to create interface for every service and dao?
2) How should be project structure for spring mvc?
What is the purpose of interface
Short answer: dependency injection
Long answer: You see, we do not want concrete implementation and strong coupling in our application. Interfaces serves that purpose, with or without Spring. Spring is a framework that heavily leverages on that. With an interface, you can write multiple implementations of a single logic by defining a contract (interface methods) that describes what is the parameter and return types but you did not specify how is it done. Which gives you a lot of flexibility in writing different Spring beans (Impl classes) that do that. List in Java is an interface, then you have implementations like LinkedList and ArrayList
How should Spring MVC project be structured
Short answer: anyway you like
Long answer: Are you using Spring MVC as API server or serving views like JSP/Thymeleaf? If I am writing an API I would have Controllers (entry point and spring specific features), Facades (business logic that is pure Java without framework classes), and DAO/Services (depending if data comes from database or 3rd party API, maybe both) at bare minimum. For MVC I would have almost similar setups but depending on your agreement with your API provider I might scrap the service layer and focuses more on the Javascript side. In this day and age I'd advise against using JSP/Freemarker. They are a lot slower to develop compared to having let's say React + API server in any language.

Is it advantageous to create a Spring bean when I can access the only static method directly with class name

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.

Dependency Injection in OSGI environments

First some background:
I'm working on some webapp prototype code based on Apache Sling which is OSGI based and runs on Apache Felix. I'm still relatively new to OSGI even though I think I've grasped most concepts by now. However, what puzzles me is that I haven't been able to find a "full" dependency injection (DI) framework. I've successfully employed rudimentary DI using Declarative Services (DS). But my understanding is that DS are used to reference -- how do I put this? -- OSGI registered services and components together. And for that it works fine, but I personally use DI frameworks like Guice to wire entire object graphs together and put objects on the correct scopes (think #RequestScoped or #SessionScoped for example). However, none of the OSGI specific frameworks I've looked at, seem to support this concept.
I've started reading about OSGI blueprints and iPOJO but these frameworks seem to be more concerned with wiring OSGI services together than with providing a full DI solution. I have to admit that I haven't done any samples yet, so my impression could be incorrect.
Being an extension to Guice, I've experimented with Peaberry, however I found documentation very hard to find, and while I got basic DI working, a lot of guice-servlet's advanced functionality (automatic injection into filters, servlets, etc) didn't work at all.
So, my questions are the following:
How do declarative services compare to "traditional" DI like Guice or Spring? Do they solve the same problem or are they geared towards different problems?
All OSGI specific solutions I've seen so far lack the concept of scopes for DI. For example, Guice + guice-servlet has request scoped dependencies which makes writing web applications really clean and easy. Did I just miss that in the docs or are these concerns not covered by any of these frameworks?
Are JSR 330 and OSGI based DI two different worlds? iPOJO for example brings its own annotations and Felix SCR Annotations seem to be an entirely different world.
Does anybody have experience with building OSGI based systems and DI? Maybe even some sample code on github?
Does anybody use different technologies like Guice and iPOJO together or is that just a crazy idea?
Sorry for the rather long question.
Any feedback is greatly appreciated.
Updates
Scoped injection: scoped injection is a useful mechanism to have objects from a specific lifecycle automatically injected. Think for example, some of your code relies on a Hibernate session object that is created as part of a servlet filter. By marking a dependency the container will automatically rebuild the object graph. Maybe there's just different approaches to that?
JSR 330 vs DS: from all your excellent answers I see that these are a two different things. That poses the question, how to deal with third party libraries and frameworks that use JSR 330 annotations when used in an OSGI context? What's a good approach? Running a JSR 330 container within the Bundle?
I appreciate all your answers, you've been very helpful!
Overall approach
The simplest way to have dependency injection with Apache Sling, and the one used throughout the codebase, is to use the maven-scr-plugin .
You can annotate your java classes and then at build time invoke the SCR plugin, either as a Maven plugin, or as an Ant task.
For instance, to register a servlet you could do the following:
#Component // signal that it's OSGI-managed
#Service(Servlet.class) // register as a Servlet service
public class SampleServlet implements Servlet {
#Reference SlingRepository repository; // get a reference to the repository
}
Specific answers
How do declarative services compare to "traditional" DI like Guice or Spring? Do they solve the same problem or are they geared towards different problems?
They solve the same problem - dependency injection. However (see below) they are also built to take into account dynamic systems where services can appear or disappear at any time.
All OSGI specific solutions I've seen so far lack the concept of scopes for DI. For example, Guice + guice-servlet has request scoped dependencies which makes writing web applications really clean and easy. Did I just miss that in the docs or are these concerns not covered by any of these frameworks?
I haven't seen any approach in the SCR world to add session-scoped or request-scoped services. However, SCR is a generic approach, and scoping can be handled at a more specific layer.
Since you're using Sling I think that there will be little need for session-scoped or request-scoped bindings since Sling has builtin objects for each request which are appropriately created for the current user.
One good example is the JCR session. It is automatically constructed with correct privileges and it is in practice a request-scoped DAO. The same goes for the Sling resourceResolver.
If you find yourself needing per-user work the simplest approach is to have services which receive a JCR Session or a Sling ResourceResolver and use those to perform the work you need. The results will be automatically adjusted for the privileges of the current user without any extra effort.
Are JSR 330 and OSGI based DI two different worlds? iPOJO for example brings its own annotations and Felix SCR Annotations seem to be an entirely different world.
Yes, they're different. You should keep in mind that although Spring and Guice are more mainstream, OSGi services are more complex and support more use cases. In OSGi bundles ( and implicitly services ) are free come and go at any time.
This means that when you have a component which depends on a service which just became unavailable your component is deactivated. Or when you receive a list of components ( for instance, Servlet implementations ) and one of them is deactivated, you are notified by that. To my knowledge, neither Spring nor Guice support this as their wirings are static.
That's a great deal of flexibility which OSGi gives you.
Does anybody have experience with building OSGI based systems and DI? Maybe even some sample code on github?
There's a large number of samples in the Sling Samples SVN repository . You should find most of what you need there.
Does anybody use different technologies like Guice and iPOJO together or is that just a crazy idea?
If you have frameworks which are configured with JSR 330 annotations it does make sense to configure them at runtime using Guice or Spring or whatever works for you. However, as Neil Bartlett has pointed out, this will not work cross-bundles.
I'd just like to add a little more information to Robert's excellent answer, particularly with regard to JSR330 and DS.
Declarative Services, Blueprint, iPOJO and the other OSGi "component models" are primarily intended for injecting OSGi services. These are slightly harder to handle than regular dependencies because they can come and go at any time, including in response to external events (e.g. network disconnected) or user actions (e.g. bundle removed). Therefore all these component models provide an additional lifecycle layer over pure dependency injection frameworks.
This is the main reason why the DS annotations are different from the JSR330 ones... the JSR330 ones don't provide enough semantics to deal with lifecycle. For example they say nothing about:
When should the dependency be injected?
What should we do when the dependency is not currently available (i.e., is it optional or mandatory)?
What should we do when a service we are using goes away?
Can we dynamically switch from one instance of a service to another?
etc...
Unfortunately because the component models are primarily focused on services -- that is, the linkages between bundles -- they are comparatively spartan with regard to wiring up dependencies inside the bundle (although Blueprint does offer some support for this).
There should be no problem using an existing DI framework for wiring up dependencies inside the bundle. For example I had a customer that used Guice to wire up the internal pieces of some Declarative Services components. However I tend to question the value of doing this, because if you need DI inside your bundle it suggests that your bundle may be too big and incoherent.
Note that it is very important NOT to use a traditional DI framework to wire up components between bundles. If the DI framework needs to access a class from another bundle then that other bundle must expose its implementation details, which breaks the encapsulation that we seek in OSGi.
I have some experience in building applications using Aries Blueprint. It has some very nice features regarding OSGi services and config admin support.
If you search for some great examples have a look at the code of Apache Karaf which uses blueprint for all of its wiring.
See http://svn.apache.org/repos/asf/karaf/
I also have some tutortials for Blueprint and Apache Karaf on my website:
http://www.liquid-reality.de/display/liquid/Karaf+Tutorials
In your environment with the embedded felix it will be a bit different as you do not have the management features of Karaf but you simply need to install the same bundles and it should work nicely.
I can recommend Bnd and if you use Eclipse IDE sepcially Bndtools as well. With that you can avoid describing DS in XML and use annotations instead. There is a special Reference annotation for DI. This one has also a filter where you can reference only a special subset of services.
I am using osgi and DI for current my project, I've choosed gemini blueprint because it is second version of SPRING DYNAMIC MODULES, Based on this information I suggest you to read Spring Dynamic Modules in Action. This book will help you to understand some parts and points how to build architecture and why is it good :)
Running into a similar architecture problem here - as Robert mentioned above in his answer:
If you find yourself needing per-user work the simplest approach is to
have services which receive a JCR Session or a Sling ResourceResolver
and use those to perform the work you need. The results will be
automatically adjusted for the privileges of the current user without
any extra effort.
Extrapolating from this (and what I am currently coding), one approach would be to add #param resourceResolver to any #Service methods so that you can pass the appropriately request-scoped object to be used down the execution chain.
Specifically we've got a XXXXService / XXXXDao layer, called from XXXXServlet / XXXXViewHelper / JSP equivalents. So managing all of these components via the OSGI #Service annotations, we can easily wire up the entire stack.
The downside here is that you need to litter your interface design with ResourceResolver or Sessions params.
Originally we tried to inject ResourceResolverFactory into the DAO layer, so that we could easily access the session at will via the factory. However, we are interacting with the session at multiple points in the hierarchy, and multiple times per request. This resulted in session-closed exceptions.
Is there a way to get at that per-request ResourceResolver reliably without having to pass it into every service method?
With request-scoped injection on the Service layers, you could instead just pass the ResourceResolver as a constructor arg & use an instance variable instead. Of course the downside here is you'd have to think about request-scope vs. prototype-scope service code and separate out accordingly.
This seems like it would be a common problem where you want to separate out concerns into service/dao code, leaving the JCR interactions in the DAO, analogous to Hibernate how can you easily get at the per-request Session to perform repo operataions?

What are the benefits of Spring Framework in Terms of Testing Application?

We have heard a lot about Benefits of Spring like it offers loose coupling, dependency injection, inversion of control etc but from testing point of view, I have couple of question.
What are the advantages of Spring Framework in terms of testing an application?
Why Application developed using Spring as considered my testable as opposed to other Web Application?
Please provide some useful examples as then it would be much more easier to understand explanation. I am new to Spring as such and want to understand precise benefits offered by Spring Framework from Application Developer point of view ?
An application geared towards dependency injection is typically more testable because resources are easily replaced with test-oriented resources. Consider a service object that uses a data access object; in production, you'd inject a DAO that talked to a backend data store. But for each test you could create a DAO that returned specific, known data; this allows you to focus on the object being tested.
Spring is one of many dependency injection frameworks for Java, albeit the most popular; any DI framework is going to give you this kind of benefit.

Runtime dependency injection with Spring

My current project is leveraging Spring, and our architect has decided to let Spring manage Services, Repositories and Factory objects, but NOT domain objects. We are closely following domain driven design. The reasoning behind not using spring for domain objects is primarily that spring only allows static dependency injection. What i mean by static dependency injection is that dependencies are specified inside xml configuration and they get "frozen".
I maybe wrong, but my current understanding is that even though my domain only leverages interfaces to communicate with objects, but spring's xml configuration forces me to specify a concrete dependency. hence all the concrete dependencies have to be resolved at deployment time. Sometimes, this is not feasible. Most of our usecases are based on injecting a particular type based on the runtime data or a message received from an end user.
Most of our design is following command pattern. hence, when we recieve a command, we would like to construct our domain model and based on data received from a command, we inject particular set of types into our aggregate root object. Hence, due to lack of spring's ability to construct a domain model based on runtime data, we are forced to use static factory methods, builders and Factory patterns.
Can someone please advise if spring has a problem to the above scenario ?
I could use AOP to inject dependencies, but then i am not leveraging spring's infrastructure.
I suggest you read the section in the Spring docs concerning Using AspectJ to dependency inject domain objects with Spring.
It's interesting that you said "I could use AOP to inject dependencies, but then i am not leveraging spring's infrastructure, " considering that AOP is a core part of Spring's infrastructure. The two go very well together.
The above link allows you to have Spring's AOP transparently inject dependencies into domain objects that are creating without direct reference to the Spring infrastructure (e.g. using the new operator). It's very clever, but does require some deep-level classloading tinkering.
Spring's dependency injection/configuration is only meant for configuring low-level technical infrastructure, such as data sources, transaction management, remoting, servlet mount-points and so forth.
You use spring to route between technical APIs and your services, and inside those services you just write normal Java code. Keeping Spring away from your domain model and service implementations is a good thing. For a start , you don't want to tie your application's business logic to one framework or let low-level technical issues "leak" into your application domain model. Java code is much easier to modify in the IDE than spring's XML config, so keeping business logic in java let's you deliver new features more rapidly and maintain the application more easily. Java is much more expressive than spring's XML format so you can more clearly model domain concepts if you stick to plain Java.
Spring's dependency injection (and dependency injection in general) is basically for wiring together Services, Repositories and Factories, etc. It's not supposed to directly handle things that need to be done dynamically in response to commands, etc., which includes most stuff with domain objects. Instead, it provides control over how those things are done by allowing you to wire in the objects you want to use to do them.

Categories