使用Spring Framework的十二个理由

今天在外网看到一篇文章讲述了在项目中使用 Spring 的 12 个理由,觉得非常不错,转载如下。

I am proud to say I have been a Spring developer since 2004. I have used Spring Framework in all my projects since then.

The projects did differ in the Spring modules that came into play based on the clients needs.

There are some modules and projects I have never worked with and I will identify them as we go along.

Having said that, I am trying some of these new modules in my current projects. I may come back to update my familiarity with them in future as I learn more.

The term ‘Spring developer’ needs a quick mention. With it, I want to clarify how I leveraged Spring Framework and its modules in my projects as we go along.

This will help you understand where Spring Framework can come into play in your projects.

You will get to understand what it can or cannot do based on some real use case scenarios I provide below. I will refer to different projects within Spring Framework Ecosystem throughout the post.

Some of these terms below may be new to you. For now, It is more important to understand the problem they are solving. I will revisit them one by one in the future posts.

Here are twelve reasons to use Spring Framework in your projects in no particular order:

1. Use Spring Framework for writing web applications

It did not start out this way. But Spring MVC is now the de facto framework for java web applications development.

Most of my projects used Spring MVC. Other frameworks in space include Struts, JSF, Tapestry, GWT, Play etc.

Most other web applications provide integration with Spring Framework. With Spring MVC, this support is natural and built-in.

And Spring MVC delivers.

You are not bound to any container lifecycle that you need to manipulate. Spring does this behind the scenes for you. If you do decide to participate in the lifecycle, Spring exposes methods that can be overridden.

Spring MVC provides special form tags and validation out of the box. It supports the easy availability of model. It handles the request to model mapping.

You can add custom converters to handle special data in your forms. I will discuss this in a new light with code and samples soon.

Spring Web Flow LogoSpring Web Flow

Spring MVC makes sense for most of the web based applications. If you have a statefulapplication, I suggest you look at Spring Web Flow.

Only one of my projects leveraged Spring Web Flow. That was a long time ago.

Spring Web Flow lets you build a wizard – a set of screens a user must go through before saving the data. Spring Web Flow will save you from having to store a lot of temporary data.

A mortgage application would be a stateful application. A flight reservation system is another example.

2. Use Spring Framework for exposing RESTful services

Use Spring MVC to expose your services as RESTful URLs. Jersey is another alternative.

Spring HATEOAS sits on top of Spring MVC and helps it better represent resources.

Spring HATEOAS LogoSpring HATEOAS

HATEOAS stands for Hypermedia as the Engine of Application State.

I will try and give a quick and dirty explanation for HATEOAS. I understand the concept, but I haven’t used it in my projects yet.

A web services developer provides a contract to its consumer before they can call it.

In SOAP world, this was the stub or the interface that let the client know which methods were available.

In REST, we have been building URLs with appropriate data to send. We still needed to know what the server expects here.

In Hypermedia, the resource identifiers will give you a clue about what it expects. This will give you insight into how you can further interact with it. A small convention over configuration on the web, if you will.

I used Jersey for one of my projects as opposed to Spring MVC. Jersey follows JSR specification for creating RESTful web services.

Spring MVC deviates from the specification in a slight way. It is easy to convert the API from Spring MVC to Jersey and vice versa. I will discuss MVC in future but for now it stands for Model, View and Controller. MVC helps define a clear separation of concerns amongst layers. For instance, your view should not depend on how java models it.

In my opinion, when in doubt always go with Spring MVC. If you ever need to support a web page with JSP, Jersey can’t help you. Jersey deals with REST only. Spring MVC will give you best of both worlds.

If your client wants to use jQuery on top of JSPs, you can do so with Spring MVC. If, at a later point of time, you want to use a Javascript MVC framework, Spring MVC will continue to support you.

Few popular Javascript MVC frameworks are AngularJS, Ember, and Backbone.js

Javascript MVC frameworks bring structure to the javascript code. It keeps the code modular and clear.

CSS Frameworks bring ease and structure to the web design code. Bootstrap is the most popular CSS Framework out there. Foundation is another one.

Spring MVC brings structure to the servlet programming model. It keeps the data model separate from view. Servlets embedded HTML code a long time ago. Struts MVC Framework solved that problem. Spring MVC came later.

Javascript MVC frameworks are like Spring MVC but on the javascript layer. With Javascript MVC frameworks, you build your web pages separate from your server logic.

The two layers then communicate and exchange data with servers via RESTful URLs.

More on MVC frameworks in future posts.

3. Use Spring Framework to secure your web applications.

For all my projects that involved web development, I have used Spring Security. A two-minute introduction is below.

Spring Security LogoSpring Security

Spring Security intercepts web URLs. Here are few examples:

You can tell it that all URLs with a specific pattern e.g. /static are accessible to all users.

You can tell it that all URLs with a specific pattern e.g. /admin are only available to users with a specific role. e.g. ROLE_ADMIN.

You can also add annotations on the java methods to make them secure. I will discuss this in length in a future post.

Spring Security provides both authentication as well as authorization.

Authentication helps identify who you are.

Authorization helps identify what you can do in the system.

When starting a fresh project, I integrate spring security and use in-memory authentication.

In-memory authentication premise is simple. You hard code a bunch of username, password, role combination into a file or within your XML or java code.

Spring Security would then let you in using either one of them and give you the role for that user. This helps developers continue with the application development.

Later, you could plug in a different authentication provider. And there are no code changes to the business logic as a result of this.

Most projects I have worked with pull credentials from database tables. Once the database is available, we switch to a database authentication provider.

For two of my projects, I have authenticated users against LDAP via Spring LDAP.

Spring LDAP LogoSpring LDAP

For one of my other projects, our users were database schema owners. Spring security supported custom authentication where we had to proxy as database users.

One of the projects I worked on required BASIC authentication support.

Three of my projects leveraged the following Single Sign-On (SSO) solutions for pre-authentication.

  1. Oracle Based Single Sign-On (OBSSO) . I used Spring Security Custom authentication here to integrate it with my applications.
  2. CA Siteminder aka CA Single Sign-On. Spring Security provides a built-in module for this. In my opinion, this is the easiest single sign-on solution to work with. CA Siteminder is a paid solution.
  3. Apereo’s Central Authentication Service (CAS). This is open source Single Sign-On solution that came out of Yale University. If you can’t afford CA Siteminder, CAS may work for you. It is a free and open source solution. Apereo provides jars for integration with Spring Security.

4. Use Spring Framework for communicating with databases.

For most of my projects, I used Spring ORM with hibernate underneath. One of the projects used Spring JPAwhile the others were direct hibernate calls. ORM is the Object Relational Mapping. It is a way to represent your tables into java objects and vice versa. Hibernate is the most popular ORM Framework. myBatis is another one.

One of the projects used myBatis instead of Hibernate. mybatis-spring module came in handy there. MyBatis used to be iBatis before iPhone and iMac and iPad came along.

And if you are dealing with a lot of existing plain old JDBC code, my suggestion would be to use Spring JDBC.

Let Spring JDBC close your statements and connections. Use Spring JDBC to integrate connection pooling. Let Spring handle your database transactions as well.

Spring Data LogoSpring Data

I also ran into situations where I was using hibernate for ORM but had to call a pl/SQL procedure in Oracle. Hibernate expects your procedure in a certain way. So, I used Spring JDBC to call procedures if they didn’t fit in the structure required by hibernate.

If you are starting a new project, I would recommend using Spring Data. It sits on top of Spring ORM.

With Spring Data, you don’t write standard CRUD operations. They come built-in. I will explain this in a future post.

I have used Spring Data for Oracle and MongoDB now without any issues. I know it has support for other NoSQL and graph databases like Redis, Cassandra, Neo4j, Couchbase, Elasticsearch and Solr.

5. Use Spring Framework for handling long running jobs.

I have worked at two projects where the database queries would take hours to finish. I will explain the reason below in a second.

You can’t expect your users who kick off this report to wait that long, though.

For one, Your browser requests will die based on the application server settings. For instance, tomcat has a default setting of 30 minutes before timing out user request. So the process may be running in the background but the user can’t see it anymore.

One of the projects had accounting updates to make to millions of rows. Here we used Spring Batch.

Spring Batch LogoSpring Batch

In this case, our web request would kick off a Spring Batch Job and immediately return with a Job Id. So the user is not waiting.

I can then use the job id to check the status of the job and keep the user updated of the progress.

This could be an email notification to the user. Or these days, you could leverage web sockets to push any notification to the user while he is still online.

Spring Batch also provides you a way to notify a system in case of status changes. So you could tell Spring Batch to update a row in the database or send an email once the job status changed. The possibilities are endless here.

The second project had reporting data to pull from a massive datamart. The reporting tool we used handled it for us. But the concept was the same with it running async and handing us an id.

Spring Batch expects a certain database schema and it has a learning curve.

Spring Batch does not make things fast. But it will ensure data integrity and consistency in your job.

You can tell it to retry a job X number of times if it fails. You could tell it how to handle failures.

Try coding this yourself and you will appreciate Spring Batch even more.

6. Use Spring Framework to handle external resources or systems you have to work with.

In one of my projects, Our client would send us reports as XML files via web services. These XMLs were small, but there was no definite way to tell when these files would come in. We had 100k XML files come in six months on average.

Our goal was to intercept these files as they came in and process them for our system intake.

Spring Integration LogoSpring Integration

This is a typical scenario for a service that depends on an external system.

We used Spring Integration for this task. We set up a file poller for the directory of incoming files. Once the file came in, the event would get triggered. We would then push it through our workflow.

The code to handle the incoming file would stay separate from the rest of the workflow. This kept the external party dependency away from the rest of the system and made testing easy.

7. Use Spring Framework for testing purposes.

I once worked on a Struts 1.x based web application with EJB3 implementation underneath. They needed to perform some clean up of the data for their testing environment on a regular basis.

So, I created a simple standalone Spring JDBC project and ran a bunch of updates on the tables. I learned more about the project and data structure via this effort than from few months code sifting.

8. Use Spring Framework for standalone java projects.

I worked on a product that was a standalone CLI (command line interface) sold to clients. It was Java based business rules engine with heavy XML parsing.

When things went wrong, it was hard to test which component failed to deliver.

So, I introduced Spring Framework in a test package within the project. I used Spring Context, Spring Test, and JUnit to call these different components.

The testers had an XML and unit tests that could prep the data before each call.

9. Use Spring Framework to convert your application into an executable.

Going back to the Spring Batch project. We were kicking off these jobs from a web page based on user’s input.

Spring Boot LogoSpring Boot

The application was using Spring Framework and its different modules already. But an external team needed to kick off these batch jobs from their end on their own schedule.

So, I created an executable using Spring Boot to point to the main Spring Batch Job. It was the same job that we were calling from our web application. It was the same codebase.

The external team could call this executable nightly or whenever now. There was no code change needed from our side.

10. Use Spring Framework to integrate Social Media into your applications.

I used to have a startup that failed two years ago. It wasn’t due to technology, though.

I used Spring Social to allow users to sign into my application. The application would allow any Facebook, Google, Linkedin or Twitter user to sign up as a result.

Spring Social LogoSpring Social

Spring Social leverages OAuth underneath to make this possible. These social media accounts expose OAuth APIs to allow authentication.

I also used Spring Mobile to provide a mobile user experience of my application. I won’t recommend this, though.

Spring Mobile allows you to customize your pages so you can tweak them for mobile users. It implies having to change the code to accommodate both users.

This is cumbersome and not the best bang for the buck.

If I were starting out, I would leverage Bootstrap and Angular JS to build out the application.

Bootstrap is responsive CSS Framework and Angular JS is mobile friendly javascript MVC Framework.

As I write this, Angular 2.x is in works. Angular2 is a mobile-first platform.

11. Use Spring Framework to come up with a quick prototype.

If you are looking to expose few database tables as a set of screens, I recommend you look into Spring Roo. You will get a working CRUD application that will maintain data integrity out of the box.

You can then use the app to allow data manipulation without going into the database.

Sometimes you want to ask your client for important columns to show on screen. Spring Roo could be a quick prototype for client feedback in that case. You can do this with Grails even faster. If you know Groovy, maybe you’d consider this.

12. Use Spring Framework to get Started.

Last but not least, Spring Framework helps you get started.

Use Spring Boot to create the web or standalone application in a span of few minutes. If you are a Groovy guy and used Grails, you have the same power in Spring Boot for java now and then some.

Spring Cloud LogoSpring Cloud

Use Spring Cloud to build micro services fast. The micro-services are already configured for registration and discovery. And that’s all I know at this point about Spring Cloud.

I have never used Spring Cloud in any of my projects.

Use Spring XD to build a distributed system for your big data applications.

I explained earlier how Spring Batch can fail-proof your long running jobs.

If you have a web application that spawns these jobs, you need a way to abstract Spring Batch from the rest of the app. Spring Integration comes in handy here.

Spring XD LogoSpring XD

If you leverage Hadoop for big data, Spring Batch can act as a backbone. You could segregate the work as Tasklets. These tasklets coordinate their flow using Steps. These Steps can combine to become a Job.

It is easy to propose Spring Batch alone. Combine it with Spring Integration and you have a distributed system per se.

But what about scalability and monitoring of these different moving parts?

How do you provide any real-time analytics in a system like this?

With the two questions above, we have identified a use case for Spring XD.

I have never used Spring XD for any of my projects.

Summary

I hope you were able to get an idea of what Spring Framework does. And if the terms were new, I hope you were able to look past them. These terms I discussed above fit into Spring Ecosystem in two ways – Spring modules and Spring Projects. I plan to discuss them next. Regardless, I hope you can decide now if it makes sense to use Spring Framework in your projects.

It would make my day if you shared how you have used or plan to use Spring Framework in your own projects.

I am always interested in different approaches developers take to address a specific problem.

If you thought of a different solution to a problem I described above, what would it be? Please don’t hesitate to share it below.

I promise to to give it a due consideration.

Please take a few minutes and say hi either in the comments below or connect with me on Facebook here. I would love to stay in touch.

Thanks!