, , ,

When developing Spring Boot applications, you need to tell the Spring Framework where to look for Spring components. Using component scan is one method of asking Spring to detect Spring managed components. Spring needs the information to locate and register all the Spring components with the application context when the application starts.

Spring can auto scan, detect, and instantiate components from pre-defined project packages. Spring can auto scan all classes annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository

In this post, I will discuss how Spring component scanning works.

Sample Application

Let us create a simple Spring Boot application to understand how component scanning works in Spring.

We will start by writing few components.

DemoBeanA.java

DemoBeanB1.java

DemoBeanB2.java

DemoBeanB3.java

DemoBeanC.java

DemoBeanD.java

The @SpringBootApplication Annotation

Spring needs to know which packages to scan for annotated components in order to add them to the IoC container. In a Spring Boot project, we typically set the main application class with the @SpringBootApplication annotation. Under the hood, @SpringBootApplication is a composition of the @Configuration, @ComponentScan, and @EnableAutoConfiguration annotations. With this default setting, Spring Boot will auto scan for components in the current package (containing the @SpringBoot main class) and its sub packages.

To know more about these annotations go through my Spring Framework Annotations post.

Note: It is recommended that you locate your main application class in a root package above the component classes of the application.

The code to create the main class and access components is this.

BlogPostsApplication.java

The output of running the main class is this.
Output of BlogPostsApplication.java class

As you can notice, all the classes in the sub packages of the main class BlogPostsApplication are auto scanned by Spring.

@ComponentScan – Identifying Base Packages

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.

The basePackageClasses attribute is a type-safe alternative to basePackages. When you specify basePackageClasses, Spring will scan the package (and subpackages) of the classes you specify. 

A Java class annotated with @ComponentScan with the basePackageClassesattribute is this.

BlogPostsApplicationWithComponentScan.java

The output on running the main class is this.
Output of BlogPostsApplicationWithComponentScan.java Class

The @ComponentScan annotation uses the basePackages attribute to specify three packages (and subpackages) that will be scanned by Spring. The annotation also uses the basePackageClasses attribute to declare the DemoBeanB1 class whose package Spring Boot should scan.

As demoBeanC is in a different package, Spring did not find it during component scanning.

Component Scanning Filters

You can configure component scanning by using different type filters that Spring provides.

By using filters, you can further narrow the set of candidate components from everything in basePackages to everything in the base packages that matches the given filter or filters.

Filters can be of two types: include and exclude filters. As their names suggest, include filters specify which types are eligible for component scanning, while exclude filters specify which types are not.

You can use the include and/or exclude filters with or without the default filter. To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.

The code to disable the default filter is this.

BlogPostsApplicationDisablingDefaultFilters.java

In the preceding code, the value member defines the specific guru.springframework.blog.componentscan.example.demopackageA package to scan, while the useDefaultFilters member disables the default filter.

The output on running the main class is this.
Output of BlogPostsApplicationDisablingDefaultFilters.java Class

As you can notice, the class DemoBeanA in the package demopackageA is unavailable when the useDefaultFilters element of the @ComponentScan annotation is set to false.

Component Scanning Filter Types

Spring provides the FilterType enumeration for the type filters that may be used in conjunction with @ComponentScan.

The available FilterType values are:

  • FilterType.ANNOTATION: Include or exclude those classes with a stereotype annotation
  • FilterType.ASPECTJ: Include or exclude classes using an AspectJ type pattern expression
  • FilterType.ASSIGNABLE_TYPE: Include or exclude classes that extend or implement this class or interface
  • FilterType.REGEX: Include or exclude classes using a regular expression
  • FilterType.CUSTOM: Include or exclude classes using a custom implementation of the org.springframework.core.type.TypeFilter interface

Include Filters

With include filters, you can include certain classes to be scanned by Spring. To include assignable type, use the includeFilters element of the @ComponentScan annotation with FilterType. ASSIGNABLE_TYPE. Using this filter, you can instruct Spring to scan for classes that extends or implements the class or interface you specify.

The code to use the includeFilters element of @ComponentScan is this.

BlogPostsApplicationIncludeFilter.java

The output on running the main class is this.
Output of BlogPostsApplicationIncludeFilter.java Class

As shown in the preceding figure, Spring detected and used the demoBean3 component that extends demoBean2.

Include Filters using Regex

You can use regular expressions to filter out components to be scanned by Spring. Use the includeFiltersnested annotation @ComponentScan.Filter type FilterType.REGEXto set a pattern.

The code to use an exclude filter based on regular expression is this.

BlogPostsApplicationFilterTypeRegex.java

The output of the following code snippet is this.
Output of BlogPostsApplicationFilterTypeRegex.java Class
As shown in the preceding figure, the classes whose names end with A, or 2 are detected by Spring.

Exclude Filters

The @ComponentScan annotation enables you to exclude those classes that you do not want to scan.

The code to use an exclude filter is this.

BlogPostsApplicationExcludeFilter.java

In this code, the nested annotation @ComponentScan.Filter is used to specify the filter type as FilterType.ASSIGNABLE_TYPE and the base class that should be excluded from scanning.

The output is this.
Output of using the FilterType.ASSIGNABLE_TYPE type

As you can see, the class DemoBeanB2 has been excluded from being scanned.

Summary

When using Spring Boot, most of the time the default auto scanning will work for your project. You only need to ensure that your @SpringBoot main class is at the base package of your package hierarchy. Spring Boot will automatically perform a component scan in the package of the Spring Boot main class and below.

One related annotation that I didn’t mention in this post is @EntityScan is more about JPA entity scanning rather than component scanning. The @EntityScan annotation, unlike @ComponentScan does not create beans. It only identifies which classes should be used by a specific persistence context.

4
Share
,

An exciting feature in Spring Framework 5 is the new Web Reactive framework for allows reactive web applications. Reactive programming is about developing systems that are fully reactive and non-blocking. Such systems are suitable for event-loop style processing that can scale with a small number of threads.

Spring Framework 5 embraces Reactive Streams to enable developing systems based on the Reactive Manifesto published in 2014.

The Spring Web Reactive framework stands separately from Spring MVC. This is because Spring MVC is developed around the Java Servlet API, which uses blocking code inside of Java. While popular Java application servers such as Tomcat and Jetty, have evolved to offer non-blocking operations, the Java Servlet API has not.

From a programming perspective, reactive programming involves a major shift from imperative style logic to a declarative composition of asynchronous logic.

In this post, I’ll explain how to develop a Web Reactive application with the Spring Framework 5.0.

Spring Web Reactive Types

Under the covers, Spring Web Reactive is using Reactor, which is a Reactive Streams Implementation. The Spring Framework extends the Reactive Streams Publisher interface with the Flux and Mono  reactive types.

The Flux  data type represents zero to many objects. (0..N)

While the Mono  data type is zero to one.  (0..1)

If you’d like a deeper dive on reactive types, check on Understanding Reactive Types by Sebastien Deleuze.

The Web Reactive Application

The application that we will create is a web reactive application that performs operations on domain objects. To keep it simple, we will use an in memory repository implementation to simulate CRUD operations in this post. In latter posts, we will go reactive with Spring Data.

Spring 5 added the new spring-webflux module for reactive programming that we will use in our application. The application is composed of these components:

  • Domain object: Product in our application.
  • Repository: A repository interface with an implementation class to mimic CRUD operations in a Map.
  • Handler: A handler class to interact with the repository layer.
  • Server: A non-blocking Web server with single-threaded event loop. For this application, we will look how to use both Netty and Tomcat to serve requests.

The Maven POM

For web reactive programming, you need the new spring-webflux and reactive-stream modules as dependencies in your Maven POM.

To host the application in a supported runtime, you need to add its dependency. The supported runtimes are:

  • Tomcat: org.apache.tomcat.embed:tomcat-embed-core
  • Jetty: org.eclipse.jetty:jetty-server and org.eclipse.jetty:jetty-servlet
  • Reactor Netty: io.projectreactor.ipc:reactor-netty
  • Undertow: io.undertow:undertow-core

The code to add dependencies for both embedded Tomcat and Netty is this.

The final dependency is for reactive serialization and deserialization to and from JSON with Jackson.

Note – This is a pre-release of Jackson, will includes non-blocking serialization and deserialization. (Version 2.9.0 was not released at time of writing)

As we are using the latest milestone release of Spring Boot, remember to add the Spring milestones repository:

Here is the complete Maven POM.

pom.xml

The Domain Object

Our application has a Product domain object on which operations will be performed. The code for the Product object is this.

Product.java

Product is a POJO with fields representing product information. Each field has its corresponding getter and setter methods. @JsonProperty is a Jackson annotation to map external JSON properties to the Product fields.

The Repository

The repository layer of the application is built on the ProductRepository interface with methods to save a product, retrieve a product by ID, and retrieve all products.

In this example, we are mimicking the functionality of a reactive data store with a simple ConcurrentHashMap implementation.

ProductRepository.java

The important things in this interface are the new Mono and Flux reactive types of Project Reactor. Both these reactive types along with the other types of the Reactive API are capable
to serve a huge amount of requests concurrently, and to handle operations with latency. These types makes operations, such as requesting data from a remote server, more efficient. Unlike traditional processing that blocks the current thread while waiting a result, Reactive APIs are non-blocking as they deal with streams of data.

To understand Mono and Flux, let’s look at the two main interfaces of the Reactive API: Publisher, which is the source of events T in the stream and Subscriber, which is the destination for those events.

Both Mono and Fluximplements Publisher. The difference lies in cardinality, which is critical in reactive streams.

The difference lies in cardinality, which is critical in reactive streams.

  • Flux observes 0 to N items and completes either successfully or with an error.
  • A Mono observes 0 or 1 item, with Mono hinting at most 0 item.

Note: Reactive APIs were initially designed to deal with N elements, or streams of data. So Reactor initially came only with Flux. But, while working on Spring Framework 5, the team found a need to distinguish between streams of 1 or N elements, so the Mono reactive type was introduced.

Here is the repository implementation class.

ProductRepositoryInMemoryImpl.java

This ProductRepositoryInMemoryImpl class uses a Map implementation to store Product objects.

In the overridden getProduct() method, the call to Mono.justOrEmpty() creates a new Mono that emits the specified item – Product object in this case, provided the Product object is not null. For a <span class="theme:classic lang:default decode:true crayon-inline"> null value, the Mono.justOrEmpty() method completes by emitting onComplete.

In the overridden getAllProducts() method, the call to Flux.fromIterable() creates a new Flux that emits the items ( Product objects) present in the Iterable passed as parameter.

In the overridden saveProduct() method, the call to doOnNext() accepts a callback that stores the provided Product into the Map. What we have here is an example of a classic non-blocking programming. Execution control does not block and wait for the product storing operation.

The Product Handler

The Product handler is similar to a typical service layer in Spring MVC. It interacts with the repository layer. Following the SOLID Principles we would want client code to interact with this layer through an interface. So, we start with a ProductHandler interface.

The code of the ProductHandler interface is this.

ProductHandler.java

The implementation class, ProductHandlerImpl is this.

ProductHandlerImpl.java

In the getProductFromRepository(ServerRequest request) method of the ProductHandlerImpl class:

  • Line 22 obtains the product ID sent as request parameter
  • Line 23 builds a HTTP response as ServerResponse for the NOT_FOUND HTTP status.
  • Line 24 calls the repository to obtain the Product as a Mono.
  • Line 25 – Line 27: Returns a Mono that can represent either the Product or the NOT_FOUND HTTP status if the product is not found.
  • Line 31 in the saveProductToRepository(ServerRequest request) method converts the request body to a Mono. Then Line 33 calls the saveProduct() method of the repository to save the product, and finally return a success status code as an HTTP response.
  • In the getAllProductsFromRepository() method, Line 37 calls the getAllProducts() method of the repository that returns a Flux< ServerResponse>. Then Line 38 returns back the Flux as a JSON that contains all the products.

Running the Application

The example web reactive application has two components. One is the Reactive Web Server. The second is our client.

The Reactive Web Server

Now it is time to wire up all the components together for a web reactive application.

We will use embedded Tomcat as the server for the application, but will also look how to do the same with the lightweight Reactive Netty.

These we will implement in a Server class.

Server.java

In this Server class:

  • Line 37 – Line 38 creates a ProductHandler initialized with ProductRepository.
  • Line 39 – Line 43 constructs and returns a RouterFunction. In Spring Reactive Web, you can relate a RouterFunction with the @RequestMapping annotation. A RouterFunction is used for routing incoming requests to handler functions. In the Server class, incoming GET requests to /{id} and / are routed to the getProductFromRepository and getAllProductsFromRepository handler functions respectively. Incoming POST requests to / are routed to the saveProductToRepository handler function.
  • Line 53 – Line 54  in the startTomcatServer() method, integrates the RouterFunction into Tomcat as a generic HttpHandler.
  • Line 55- Line 61 initializes Tomcat with a host name, port number, context path, and a servlet mapping.
  • Line 62 finally starts Tomcat by calling the start() method.

The output on executing the Server class is this.
Output of Tomcat
To use Netty instead of Tomcat, use this code:

The Client

Spring Framework 5 adds a new reactive WebClient in addition to the existing RestTemplate. The new WebClient deserves a post on its own.

To keep this post simple and limited to only accessing our reactive Web application, I will use ExchangeFunction – a simple alternative to WebClient. ExchangeFunction represents a function that exchanges a client request for a (delayed) client response.

The code of the client class, named ReactiveClient is this.

ReactiveWebClient.java

In the ReactiveClient class, Line 21 calls the ExchangeFunctions.create() method passing a ReactorClientHttpConnector, which is an abstraction over HTTP clients to connect the client to the server. The create() method returns an ExchangeFunction.

In the createProduct() method of the ReactiveClient class, Line 30 – Line 31 builds a ClientRequest that posts a Product object to a URL represented by the URI object. Then Line 32 calls the exchange(request) method to exchange the given request for a response Mono.

In the getAllProducts() method, Line 37 starts an exchange to send a GET request to get all products.

The response body is converted into a Flux and printed to the console.

With Tomcat running, the output on running the ReactiveClient class is:
Output of Reactive Web CLient

Conclusion

In this post, I showed you a very simple example of the new web reactive features inside of Spring Framework 5.

While the reactive programming features inside of Spring Framework 5 are certainly fun to use. What, I’m finding that is, even more, fun is the functional programming style of the new Spring Framework 5 APIs.

Consider the configuration of the web reactive server:

This functional style is a significant change from what we’ve become accustomed to in Spring MVC.

Don’t worry, Spring MVC is still alive and well. And even when using the Reactive features in Spring Framework 5, you can still define ‘controllers’ in the traditional declarative sense.

And maybe traditional monolithic applications will continue to declare controllers using traditional approaches?

Where I expect the functional style to really shine is in the realm of microservices. This new functional style makes it crazy easy to define small, targeted services.

I’m looking forward to seeing how the Spring community adopts the functional API, and seeing how it evolves.

2
Share

Spring Framework 5.0 is the first major release of the Spring Framework since version 4 was released in December of 2013. Juergen Hoeller, Spring Framework project lead announced the release of the first Spring Framework 5.0 milestone (5.0 M1) on 28 July 2016.

Now, a year later, we are looking forward to Release Candidate 3 (RC3) to be released on July 18th, 2017. This is expected to be the final release on the roadmap to the first GA (General Availability) release of Spring Framework 5.0.

I’m excited about the new features and enhancements in Spring Framework 5.0.

At a high level, features of Spring Framework 5.0 can be categorized into:

  • JDK baseline update
  • Core framework revision
  • Core container updates
  • Functional programming with Kotlin
  • Reactive Programming Model
  • Testing improvements
  • Library support
  • Discontinued support

JDK Baseline Update for Spring Framework 5.0

The entire Spring framework 5.0 codebase runs on Java 8. Therefore, Java 8 is the minimum requirement to work on Spring Framework 5.0.

This is actually very significant for the framework. While as developers, we’ve been able to enjoy all the new features found in modern Java releases. The framework itself was carrying a lot of baggage in supporting deprecated Java releases.

The framework now requires a minimum of Java 8.

Originally, Spring Framework 5.0 was expected to release on Java 9. However, with the Java 9 release running 18 months + behind, the Spring team decided to decouple the Spring Framework 5.0 release from Java 9.

However, when Java 9 is released (expected in September of 2017), Spring Framework 5.0 will be ready.

Core Framework Revision

The core Spring Framework 5.0 has been revised to utilize the new features introduced in Java 8. The key ones are:

  • Based on Java 8 reflection enhancements, method parameters in Spring Framework 5.0 can be efficiently accessed.
  • Core Spring interfaces now provide selective declarations built on Java 8 default methods.
  • @Nullable and @NotNull annotations to explicitly mark nullable arguments and return values. This enables dealing null values at compile time rather than throwing NullPointerExceptions at runtime.

On the logging front, Spring Framework 5.0 comes out of the box with Commons Logging bridge module, named spring-jcl instead of the standard Commons Logging. Also, this new version will auto detect Log4j 2.x, SLF4J, JUL ( java.util.logging) without any extra bridges.

Defensive programming also gets a thrust with the Resource abstraction providing the isFile indicator for the getFile method.

Core Container Updates

Spring Framework 5.0 now supports candidate component index as an alternative to classpath scanning. This support has been added to shortcut the candidate component identification step in the classpath scanner.

An application build task can define its own META-INF/spring.components file for the current project. At compilation time, the source model is introspected and JPA entities and Spring Components are flagged.

Reading entities from the index rather than scanning the classpath does not have significant differences for small projects with less than 200 classes. However, it has significant impacts on large projects.

Loading the component index is cheap. Therefore the startup time with the index remains constant as the number of classes increase. While for a compoent scan the startup time increases significantly.

What this means for us developers on large Spring projects, the startup time for our applications will be reduced significantly. While 20 or 30 seconds does not seem like much, when you’re waiting for that dozens or hundreds of times a day, it adds up. Using the component index will help with your daily productivity.

You can find more information on the component index feature on Spring’s Jira.

Now  @Nullable annotations can also be used as indicators for optional injection points. Using  @Nullable imposes an obligation on the consumers that they must prepare for a value to be null. Prior to this release, the only way to accomplish this is through Android’s Nullable, Checker Framework’s Nullable, and JSR 305’s Nullable.

Some other new and enhanced features from the release note are:

  • Implementation of functional programming style in GenericApplicationContext and AnnotationConfigApplicationContext
  • Consistent detection of transaction, caching, async annotations on interface methods.
  • XML configuration namespaces streamlined towards unversioned schemas.

Functional Programming with Kotlin

Spring Framework 5.0 introduces support for JetBrains Kotlin language. Kotlin is an object-oriented language supporting functional programming style.

Kotlin runs on top of the JVM, but not limited to it. With Kotlin support, developers can dive into functional Spring programming, in particular for functional Web endpoints and bean registration.

In Spring Framework 5.0, you can write clean and idiomatic Kotlin code for Web functional API, like this.

For bean registration, as an alternative to XML or @Configuration and @Bean, you can now use Kotlin to register your Spring Beans, like this:

spring framework 5.0 reactive is coming
Click here to learn about my new Spring Framework 5 course!

Reactive Programming Model

An exciting feature in this Spring release is the new reactive stack Web framework.

Being fully reactive and non-blocking, this Spring Framework 5.0 is suitable for event-loop style processing that can scale with a small number of threads.

Reactive Streams is an API specification developed by engineers from Netflix, Pivotal, Typesafe, Red Hat, Oracle, Twitter, and Spray.io. This provides a common API for reactive programming implementations to implement. Much like JPA for Hibernate. Where JPA is the API, and Hibernate is the implementation.

The Reactive Streams API is officially part of Java 9. In Java 8, you will need to include a dependency for the Reactive Streams API specification.

Streaming support in Spring Framework 5.0 is built upon Project Reactor, which implements the Reactive Streams API specification.

Spring Framework 5.0 has a new  spring-webflux module that supports reactive HTTP and WebSocket clients. Spring Framework 5.0 also provides support for reactive web applications running on servers which includes REST, HTML, and WebSocket style interactions.

I have a detailed post about Reactive Streams here.

There are two distinct programming models on the server-side in spring-webflux:

  • Annotation-based with @Controller and the other annotations of Spring MVC
  • Functional style routing and handling with Java 8 lambda

With Spring Webflux, you can now create WebClient, which is reactive and non-blocking as an alternative to RestTemplate.

A WebClient implementation of a REST endpoint in Spring 5.0 is this.

Spring Framework 5 - Beginner to Guru
Click Here to learn about – Spring Framework 5 – Beginner to Guru!

While the new WebFlux module brings us some exciting new capabilities, traditional Spring MVC is still fully supported in Spring Framework 5.0.

Testing Improvements

Spring Framework 5.0 fully supports Junit 5 Jupiter to write tests and extensions in JUnit 5. In addition to providing a programming and extension model, the Jupiter sub-project provides a test engine to run Jupiter based tests on Spring.

In addition, Spring Framework 5 provides support for parallel test execution in Spring TestContext Framework.
For the reactive programming model, spring-test now includes WebTestClient for integrating testing support for Spring WebFlux. The new WebTestClient, similar to MockMvc does not need a running server. Using a mock request and response, WebTestClient can bind directly to the WebFlux server infrastructure.

For a complete list enhancements in the existing TestContext framework, you can refer here.

Of course, Spring Framework 5.0 still supports our old friend JUnit 4 as well! At the time of writing, JUnit 5 is just about to go GA. Support for JUnit 4 is going to be with the Spring Framework for some time into the future.

Library Support

Spring Framework 5.0 now supports the following upgraded library versions:

Discontinued Support

At the API level, Spring Framework 5.0 has discontinued support for the following packages:

  • beans.factory.access
  • jdbc.support.nativejdbc
  • mock.staticmock of the spring-aspects module.
  • web.view.tiles2M. Now Tiles 3 is the minimum requirement.
  • orm.hibernate3 and orm.hibernate4. Now, Hibernate 5 is the supported framework.

Spring Framework 5.0 has also discontinued support for the following libraries:

  • Portlet
  • Velocity
  • JasperReports
  • XMLBeans
  • JDO
  • Guava

If you are using any of the preceding packages, it is recommended to stay on Spring Framework 4.3.x.

Summary

The highlight of the Spring Framework 5.0 is definitely reactive programming, which is a significant paradigm shift. You can look at Spring Framework 5.0 as a cornerstone release for reactive programs. For the remainder of 2017 and beyond, you can expect to see child projects implement reactive features. You will see reactive programming features added to upcoming releases of Spring Data, Spring Security, Spring Integration and more.

The Spring Data team has already implemented reactive support for MongoDB and Redis.

It’s still too early to get reactive support with JDBC. The JDBC specification itself is blocking. So, its going to be some time before we see reactive programming with traditional JDBC databases.

While Reactive Programming is the shiny new toy inside of Spring Framework 5.0, it’s not going to be supported everywhere. The downstream technologies need to provide reactive support.

With the growing popularity of Reactive Programming, we can expect to see more and more technologies implement Reactive solutions. The reactive landscape is rapidly evolving. Spring Framework 5 uses Reactor, which is Reactive Streams compliant implementation. You can read more about the Reactive Streams specification here.

11
Share

At the heart of the Spring Framework is its support of dependency injection through its Inversion of Control container. In this video, I look at using some of the advanced autowire features of Spring.

@Primary

By default, Spring will autowire by type. When you have more than one Spring Bean of a given type, you can use the @Primary annotation to give a specific bean preference over the others. If Spring cannot determine which bean should be wired by type when more than one is defined, the Spring context will fail on startup with an org.springframework.beans.factory.NoUniqueBeanDefinitionException  exception.

@Qualifier

You also have the option of using the @Qualifier annotation in conjunction with the @Autowired annotation to control how beans are autowired in Spring. While the default behavior of Spring is to autowire by type. The Qualifier allows you to specify the id or name of the bean you wish autowired into the bean.

Demonstration

The following video demonstration is a module from my Spring Core online course. In this video, I show you how to work with Spring’s autowire by type. Then show you how to fine tune Spring’s Autowire functionality through the use of Spring Profiles, the @Primary annotation, and the @Qualifier annotation.

While this is a very simple demonstration, I hope you can see the amount of control you have when you are configuring Spring to autowire beans in your application. It’s not uncommon to be dealing with more than one datasource. Naturally, you’re going to wish to have control over which datasource is autowired into your bean.

0
Share
,

I was recently asked on my Facebook page, “How do I become a Java Web Developer?” There is  really no simple answer for this question. There are many facets to becoming a Java web developer. I’ve encountered Java developers who were good front end developers, or good backend developers. By ‘front end’, I mean more of the browser side technologies – HTML, CSS, Javascript and then Java templating technologies such as Thymeleaf, Sitemesh, or just good old JSPs. Backend developers are going to have stronger skills with Java, databases (SQL and NoSQL), messaging (JMS/AQMP), and web services (SOAP / REST).

You also have what is known as a “full stack” Java developer. This is my personal skill set. A full stack developer is equally skilled as a front end developer and as a back end developer. This is probably the most difficult track to follow, just because of the diversity of technologies involved. One one day you might be debugging something in JQuery, and the next you’re performance tuning an Oracle database query. It takes time and experience to become a full stack Java developer.

Where to Start?

For aspiring developers, the technology landscape can be overwhelming. The technology landscape is always evolving too. Do you risk learning something that will soon be obsolete?

Client Side Technologies

My advice to new developers is to start with the basics. HTML, CSS, and Javascript. These technologies are core to web development. These technologies are also generic in the sense that it does not matter if you’re a Java web developer, or a Ruby web developer.

HTML

HTML – Hypertext Markup Language. This is what makes a web page. You need to have a solid understanding of HTML. Back in the beginning of the World Wide Web HTML was traditionally a file that was served by a web server to the browser. This worked great for static content. Stuff that never changed. But this is becoming rare. People want dynamic content. Thus, the HTML is no longer a static file, the HTML is generated on demand. As a Java Web Developer you’re going to be writing code that generates the HTML document for the web browser. You will need to have a solid understanding of the structure of an HTML document.

CSS

CSS – Cascading Style Sheets. This is what styles a page. It controls the fonts, the colors, the layout. While HTML defines the content of a web page, CSS defines how it looks when presented in a browser. For example, you may use one set of CSS rules for a desktop web application, and a different set of CSS rules for a mobile application. Same HTML, but two completely different looks when rendered by the browser.

Javascript

Javascript – Do stuff on the web page. Do not confuse Javascript with Java. While there are some syntax similarities, these are two completely different programming languages. Javascript is what really drives Web 2.0 applications. Through the use of Javascript, you can dynamically change the HTML/CSS based on user actions, giving the web page a more application like feel for the user.

HTTP

Hypertext Transfer Protocol – The communication between the client and the web server. I see too many web developers who do not understand HTTP. This is absolutely critical for you to understand. Especially as you get into working with AJAX. You need to know the difference between a POST and a GET. You should have memorized the meanings of HTTP status codes 200, 301, and 404 – and more. As a Java web developer you will work with HTTP everyday.

Server Side Technologies

Java

Java – The question is how to become a Java web developer. So, of course you are going to need to know the Java programming language.In addition to just Java itself, you should be familiar with the Java Servlet API. There’s a number of Java web frameworks, which obscure the usage of the Java Servlet API. When things go wrong, you’re going to need to know what’s happening under the covers.

JPA

JPA – Java Persistence API – Using the database. JPA is the standard for working with traditional relational databases in Java. Hibernate is the most popular JPA implementation in use today. As a Java web developer, you’re going to be working with databases. You’ll get getting content from the database to display on a web page, or receiving content from the user to store in the database. Java Web Developers need to know how to use JPA.

Java Application Servers

Java Application Servers – The runtime container for Java web applications. Tomcat is, by far, the most popular Java application server. There is a Java standard for a Web Application Archive file – aka WAR file. These are deployed to Application servers such as Tomcat to provide the runtime environment for your web application. A decade ago, the trend was to use a more complex coupling between your application and the application server. However, the current trend is in favor of a looser coupling between your application and the application server.

Java Frameworks

Notice so far, I have not mentioned anything about the plethora of Java frameworks available for you to use? So far, I’ve described the different technologies you will use as a Java web developer. The client side technologies are completely independent of the server side technologies. Firefox doesn’t care if the server is running Java, Python or .NET. New developers often seem to forget this.

It is possible to do Java web development without using one of the Java frameworks. If you do, you will be writing a lot code to handle things which a framework would take care of for you. Which is why when developing Java web applications, you typically will want to use one of the frameworks.

Spring Framework

The Spring Framework is an outstanding collection of tools for building large scale web applications. Exact metrics are hard to determine, but I’ve seen some estimates which say Spring is used in over 60% of Java based web applications. Which really isn’t too surprising. You have the IoC container and dependency injection from Spring Core. Spring MVC, a mature and flexible MVC based web framework. Spring Security, best in class tool for securing your website. Spring Data to help with persistence. Spring has other projects which will help you in building large scale applications.

There really is no alternative to Spring when it comes to a holistic framework. There are competing technologies against the various Spring Projects. But there is no single solution that has the depth and breadth of the Spring Framework family of projects. In my Introduction to Spring online tutorial, I give you a good overview of the major Spring Framework projects and how they are used to build enterprise class applications.

Grails

Grails is a rapid application development framework built on top of Spring. You get everything Spring, and then the productivity benefits of Groovy. I like to describe Grails as Spring with a Groovy wrapper. An oversimplification for sure, but important to remember, Spring is still under the covers.

Grails is seeing more and more use in the enterprise. One of the strengths of Grails is its outstanding community support.

Spring Roo

Spring Roo is a pure Java framework, which seems to try to do what Grails does, without Groovy. I’m not a fan of Spring Roo, and last time I checked neither was the marketplace. Spring Roo has not been widely adopted.

Play

A Scala based Framework. I have not had a chance to try out Play yet. I hear a lot of good things about Play in the marketplace. I feel Play is an interesting alternative. But it’s just not widely used in the enterprise. Not yet at least. Play is getting some encouraging traction.

JBoss Seam

JBoss Seam is probably the closest thing to an alternative to the Spring Framework. JBoss Seam follows the JEE standard. JBoss Seam is a good alternative, with good support, and adoption in the enterprise. JBoss Seam is often criticised as being slower than Spring in terms of development and performance. Some are much more critical of JBoss Seam.

Conclusion

Becoming a Java web developer is not something you can become overnight. There is no book called “Teach yourself Java Web Development in 21 days.” There are no short cuts to becoming a Java web developer. There are a lot of different technologies you need to learn and master. Each of these take time to learn.

Being a Java web developer can be a very rewarding career. You can get started just focusing on the front end, or just the backend technologies. Larger Java development shops will allow you to specialize in one area of the technologies over another.

If I was starting out as a Java web developer today, I probably would focus first on the client side technologies. The client side technologies are agnostic to the server side technologies. Thus, as you’re starting out you will have greater employment options. Compensation on the client side technologies is generally lower than the server side, but it’s a good place to start out. You can quickly gain the skills to be employable, then shift focus and broaden your skill set and later seek better employment opportunities.

2
Share
, ,

On of the things I love about the Grails environment is that it comes with a handy bootstrap.groovy file. This will run at startup of the Spring container. I frequently use this to setup expected data, or to create test data for integration / functional tests. It can be a very convenient way to seed a H2 database with startup values.

The Spring Framework itself does not have the concept for a bootstrap file like Grails does. It does however have events that we can subscribe to and functionally accomplish the same thing.

Spring Framework Events

The Spring Framework comes out the of box with a number of events, and you’re able to extend the event functionality for your own purposes.

Spring Core Events

ContextRefreshedEvent

This event is published whenever the Spring Context is started or refreshed.

ContextStartedEvent

This event is published when the Spring Context is started.

ContextStoppedEvent

This event is published when the Spring Context is stopped. In practice you will not use this event very often. It can be handy for doing cleanup work, like closing connections.

ContextClosedEvent

This event is similar to the ContextStoppedEvent, but in this case the Context can not be re-started.

Spring Boot Events

Spring Boot introduces several new events on top of the events available in the core Spring Framework.

ApplicationStartedEvent

This event is published early in the startup of a Spring Application. The Spring Context is running, but may change later in the lifecycle.

ApplicationEnvironmentPreparedEvent

This event is published when the Spring Boot Application is starting up and is first available for inspection and modification.

ApplicationPreparedEvent

This event is published when the Spring Context is fully prepared but not refreshed. At this point the Spring Beans are loaded, configured and ready for use.

ApplicationFailedEvent

This event is published when the Spring Boot Application fails to start. This event is useful for error logging or alerting.

Using Spring Framework Events

Under the scenario we want to do something on startup we have two events we can consider using. Traditionally under Spring Framework, we can use the ContextRefreshedEvent. This event has been around since the beginning of the Spring Framework.

If you’re using Spring Boot, you do have additional events to select from. I often want to use a startup event to seed data for tests, so in this case, I need the database connection to be setup. Reading about the Spring Boot Events, I thought the event I would like to use is ApplicationPreparedEvent. But in testing it out, this was not the case. I ran into some issues with getting the event listeners setup properly in the Spring Boot Context. I found better results using the ContextRefreshedEvent.

ContextRefreshedEvent Listener

Here is an example of a listener. Here, I’m injecting a simple bean to prove I got a message. In practice this bean could be whatever you wanted. You could for example inject a Spring Data Repository into your listener bean.

ContextRefresehedListener.java

EventHolderBean.java

Nothing very special about this bean. I have a event fired property, which I initialize to false. If it is true, I know the bean ‘processed’ and event.

Running the Event Bean in Spring Boot

I can run this bean in a Spring Boot Application. Below is my application class.

ContextRefreshedApplication.java

Output

In the output, you can see my console messages.

Testing the Spring Event Bean

I can also set this up in a JUnit test. This will actually run out side of Spring Boot and in a normal Spring context.

To do this I need to setup a simple Java configuration bean for my test.

ContextRefreshConfig.java

ContextRefresehedListenerTest.java

Here I have a simple JUnit test which brings up the Spring Context, and gets an instance of the Event Holder Bean. I check to make sure the event fired is set to true, proving the bean did in fact get manipulated by the event listener.

Test Output

In the output of the test, I can see the console output of the event listener.

Free Introduction to Spring Tutorial

Are you new to the Spring Framework? Checkout my Free Introduction to Spring Online Tutorial.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

1
Share
, ,

Polyglot Programming

Is the practice of programming in multiple programming languages. According to Wikipedia it is –

In computing, a polyglot is a computer program or script written in a valid form of multiple programming languages, which performs the same operations or output independent of the programming language used to compile or interpret it.

In writing the code for a recent blog post on Spring Integration, I thought it would be fun to write some of the code in Groovy. I’ve been writing in Groovy for about 7 years. I’m as fluent in Groovy as I am in Java, so its no problem for me to bounce between the two languages. If you been following my blog, you’ve probably seen me use Spock for my unit tests. Spock is a great tool. A Groovy testing framework for testing Java code.

Many Java developers who are not familiar with Groovy, view it as just a scripting language. Groovy is not just a scripting language. It is an Object Oriented Programming language, just like Java is. Some may argue that Groovy is a pure object oriented language and Java is not because of Java’s support of Primitive Types. Because unlike Java, Groovy does autoboxing of primitive types.

Its also important to understand, Groovy was never intended to be a replacement of Java. It’s written to supplement Java. As such, its very easy to mix and match code. Ultimately both Groovy and Java compile down to JVM byte code, and the compiled code is compatible.

Polyglot Programming in the Spring Framework

The Spring Framework is no stranger to Polyglot programming. The Grails community really spearheaded things with the Groovy language. In version 4 of the Spring Framework, we’re seeing a lot more support of polyglot programming around the Groovy language. But in the various Spring Framework projects we’re seeing more polyglot programming support around the Scala programming language. With Rod Johnson involved with Typesafe, I think it’s a safe bet we will see additional support of Scala in Spring in the future.

Groovy Spring Beans

It is possible to write Spring Beans in Groovy. Your application will compile and run just fine. Whenever programming for Dependency Injection, I recommend developing your code to an interface.

AddressService

When doing polyglot programming, I prefer to write the interface in Java. Now any class, written in Java or Groovy can implement the interface. You probably could write the interface in Groovy and use it in Java just fine, but there are some pitfalls of using Groovy from Java you need to be aware of. For example if you use ‘ def ‘ as a type, Java treats it as a Object  data type. Sometimes the strong typing of Java is not a bad thing. This also seems more appropriate to me when defining the interface to use.

AddressServiceImpl.groovy

You can see my Groovy class simply implements the AddressService  interface. I mark the class with the @Service("addressService")  annotation as I would a normal Java Spring Bean. 

Using a link below, you can checkout the full project. You will see the Groovy class compiles with the Java code and runs in the Spring context like any other Spring Bean.

Conclusion

In enterprise Java / Spring shops, you probably will not see much Polyglot programming. But, the Grails team uses Groovy for Spring Beans all the time. I’ve demonstrated its easy to use Groovy Spring beans outside of the Grails environment. This is not a technology issue to overcome. Culturally, I suspect it may be some time before you see polyglot programming in large scale enterprise applications. But doing polyglot programming like this is something fun to do in blog posts!

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share
,

This past week I had a real world use case for using Spring Integration Futures. I was looking into optimizing the checkout experience for a large ecommerce website. Consider what happens in a large scale website when an order is submitted. Typically, you will see a process something like:

  • Validate the place order form information
  • Verify the address against an address service
  • Verify the credit card with a payment processor
  • Verify available inventory

Each of these in a large scale enterprise are services. For example, it is common for an enterprise to subscribe to an address validation service. This helps ensure shipping accuracy. Or you’ll have a inventory service to help manage inventory levels. Normally not a problem. But when you have a black friday shopping special and thousands of users shopping on the site, managing inventory can become tricky.

Each of these services will take some time to execute. If called in sequence, the website response time slows down and impacts the user experience in the checkout flow. However, in my example here, there is no reason these service calls couldn’t be called concurrently. By calling the services concurrently, the response time now is the longest service call, not the sum of all the service calls. If each service call takes a half second, calling the services sequentially would take 2 seconds of elapsed time. Calling them concurrently only takes a half second.

A couple weeks back I wrote a blog post on testing Spring Integration Gateways.  In this use case, Spring Integration is the perfect tool. Spring Integration has a very cool feature to support asynchronous calls. When using Spring Integration Messaging Gateways, if you wrap the return time in a Java Future, Spring Integration will automatically handle the request in a different thread using a thread pool. As an application developer, this makes writing a multithreaded application very easy to do. The Spring Framework and Spring Integration handle the complexity of managing the worker threads and the thread pool.

In this post, I’m going to walk you through the configuration of the Spring Integration gateways and Spring service beans used to make these four service calls supporting my ecommerce place order example.

Spring Integration Code Examples

Command Objects

In this example, I’m going to use a command object. In a web application, this would typically have values bound to it from a form post. However, in today’s omni-channel retail environment, the website is not the only client I need to worry about. This request could be coming from a native iOS mobile application, a native Android mobile application, an in-store kiosk, or maybe a stand alone customer service application.

By using a command object, I’m decoupling my processing from the front end client. I don’t care where the request originated. Maybe it was a form post. Maybe a web service, could be a JMS request. It doesn’t really matter where the request originated.

Place Order Command

Domain Objects

For this example, I’ve created a couple domain objects. These are just simple POJOs I’m using to illustrate the example. In a real application these objects would be much more robust. 

Order

OrderLine

Product

Spring Integration Gateways

For this example, I’ve defined four different Spring Integration Messaging Gateways. Technically, I could have used just one Spring Integration Messaging Gateway, but that would have been a violation of the Single Responsibility Principle. This approach does lead to more class files. But when I need to maintain this code, I know where to look. The programming logic is clear and organized.

OrderGateway

The Order Gateway interface defines two methods. The first placeOrder  is the start of our processing chain.  This is where we will submit the command object. The second method is used in our the processing of the place order command object.

Note: notice the usage of the Java Future  for the return time of the validateOrder method. This is what instructs Spring Integration to perform the method call asynchronously using a thread pool.

AddressGateway

InventoryGateway

PaymentGateway

Spring Services

Since this is a Spring project, we’ll create our services as Spring Beans, and naturally will we be using Dependency Injection and program to an interface.

OrderService

OrderServiceImpl

The implementation of our Order Service is one of the more complex classes in this tutorial. You can see we are having Spring autowire our four Spring Integration Messaging Gateways into the class. In the placeOrderMethod , you can see I call a method on each of the four Spring Integration Gateways. Each method returns a Java Future. After all four are submitted, I go back to get the value of the Future. In this case, I’m using the Spring Errors object. If all four validation steps come back without errors, in a real system I’d persist the order to the database and do any post processing. But this is just a little sample to show off the use of Spring Integration Futures. So in this case, I’m just returning the command object either way.

Spring Integration Configuration

I had to expand on the Spring Integration configuration from our previous example. You’ll see I’m using the Spring Integration Gateway tag to define the four Spring Integration Gateways we’re using. Then I defined the Spring Integration channels and the appropriate Spring Integration service activators. Nothing new here over the previous example. Just a little more routing to take care of.

Notice how I did not define a thread pool? By default, Spring Integration is providing a thread pool for our use. You can of course define your own or update the settings of the default thread pool if needed.

si-config.xml

Running the Spring Integration Code

I’ve setup a Spock test to run the Spring Integration code in this example. 

OrderGatewayTests

When you run this Spock test you will see the following output:

Each the services I’ve wired into this example do simple print line statements out to the console. Each starts their respective output with the Id number of the thread they are running in. You can see from the output how each service is running concurrently in different threads.

Conclusion

As a programmer, Spring Integration is a very powerful tool to have in your toolbelt. You can see from this example how I’ve created a multithreaded application with a minimal amount of coding. I simply wrapped the return type I wanted on the Spring Integration Messaging Gateways with a Java Future. Spring Integration and Spring managed the thread pool for me. I didn’t need to worry about managing threads. The Spring Framework allowed me to focus on delivering the business solution, and took care of the complex boiler plate code.

Get The Code

I’ve committed the source code for this post to github. It is a Maven project which you can download and build. If you wish to learn more about the Spring Framework, I have a free introduction to Spring tutorial. You can sign up for this tutorial in the section below.

Source Code

The source code for this post is available on github. You can download it here.

0
Share
, ,

One of the things I wish to do on this blog is show you realistic examples of using the Spring Framework in Enterprise Application Development. The Spring Framework is very popular for building large scale applications. When you build a ecommerce website that might have 50,000 users on it at any given time the scope of the application you are building changes. This type of site quickly outgrows the traditional 3 tier architecture (web server / app server / database server). The ‘website’ is no longer a simple war file being deployed to Tomcat. You have a data center, with a small server farm. Load balancers, application clusters, message queuing, ‘cloud computing’, micro services. The Spring Framework was not only built for this type of application environment, it thrives in it.

Environments

When you start developing enterprise class applications, you will need to support multiple deployment environments. You’re no longer going to be testing code on your laptop, then deploying it to the production server. Frequently in the enterprise, as a developer you won’t even have access to the production environment. Companies which need to comply with regulations such as SOX, PCI and/or SAS-70 will have specialized teams which will manage code deployments to their testing (QA/UAT) and production environments. This is known as segregation of duties. A very common business practice. From my personal experience it is more stringent in large financial enterprises than it is in retail organizations. Less so in smaller companies because they simply don’t have the resources to support specialized IT staffs.

More modern development cultures will be performing CI builds and automated deployments. Teams on the bleeding edge of modern software development might even be doing continuous deployments I feel continuous deployment is probably the holy grail of software engineering, but in reality it is as rare as a great white buffalo in the wild. I do hope to see more organizations adopt continuous deployments, but it does take a very disciplined organization to get there.

Each of these environments will have its own configuration needs. As the scope of your application grows, chances are the uniqueness of each environment will grow too. The Spring Framework has some outstanding tools which are used to manage the complexities of modern enterprise application development. First, let’s consider some common challenges in the types of environments you will need to support in a large enterprise application.

Local Development

This is your development environment, running from your laptop. This is an area I often see companies absolutely fail at. Your code should be able to run locally, without the need to connect to other servers in the enterprise. Ideally, you should be able to run the code on a plane at 30,000 without a wi-fi connection.

This means:

  • You cannot use an external database. You’re not going to use the Oracle development database.
  • No interaction with other web services.
  • No JMS (MQ Series, Active MQ, Oracle AQ, etc)
  • Your build artifacts need to be locally cached (hello Maven, Ivy!!)

The Grails team does an outstanding job of supporting a local development environment of of the box. When you run Grails in dev mode, it will automatically create an in memory H2 database. Hibernate is used to generate the database tables based on your domain classes.

Continuous Integration

Continuous Integration servers can be tricky little beasts to configure for because of the different types of testing software they accomodate. You may have a project the produces a JAR file, which only has unit tests which will zip right along. You may have integration tests, like Grails does, which bring up an embedded Tomcat instance an H2 in-memory database. Your tests might even perform functional tests using something like Spock and Geb to interact with the embedded Tomcat instance. Its also not uncommon for CI servers to have automated deployment jobs – to another specialized environment.

Each of these scenarios is likely to drive special configuration needs into your application.

Development

Some companies elect to have a development environment. This is typically a production like server environment that the development team has control over. When you deploy into this environment, you will need to configure the application to interact with servers within that environment.

QA / UAT

QA or “Quality Assurance” and UAT “User Acceptance Testing” are environments for non-developer resources to test the software. In some organizations you may have both QA and UAT, or you might have one or the other. If you have both, chances are the organization has formal QA Engineers which work with the QA Environment, and Business Analysts which work with the UAT environment. These environments are often managed by a configuration management team. Sometimes developers will have access to the environment, but often they will not.

Pre-Production or Stage

Pre-Production or Stage (Staging) is an application environment that works with all the production services and supporting databases. This is an environment that allows the deployment of application code, but limits the access to that code. For a website, you might see a special url or access restricted to specific IPs, or throttled by load balancers.

This environment is not as common, but some organizations use it. Facebook deploys code something along this line.

Production

Production is the environment you end users will utilize. This is the main transactional environment and the one your business partners wish to keep operational at all times.

Summary

You can see each of these environments will have its own unique requirements. You’re going to have different database servers, different database versions, often different database vendors. You’ll have different supporting services. For example in an ecommerce website, you might have a payment gateway. In dev, it might be a mock, in test you might be using a testing gateway supplied by your payments provider, and then a different payment gateway for production.

Spring Framework Multi-Environment Support

The Spring Framework was developed from the ground up to support the challenges of supporting complex enterprise environments. You have a number of mature features in the Spring Framework to use in supporting the challenges of enterprise class applications.

Properties

The Spring Framework has excellent support of externalizing properties. “Properties” are simple string values which are externalized from your application. In the Spring Framework properties can be set the following ways:

  • In a traditional properties file. This is typically kept in the resources folder and is often named ‘application.properties’. It is by convention to use <filename>.properties.
  • Using Operating System Environment variables. Java can read values set in the Operating System as environment variables. I’ve used this in the past for things like database settings, which worked out nicely. In this case, my build artifact was easily portable between environments. Once setup, it was effectively ‘drag and drop’ for the support staff.
  • Command line variables. When starting any Java application, you have the opportunity to pass command line variables into the program. This is a handy way to make your build artifact portable. One word of caution, when examining running processes on a system, you can sometimes see the command line information which started the process. So this solution may not be the best option for password strings.

The Spring Framework Support has a number of options for sourcing in property values. One way is using the Spring Expression Language (SpEL). You can see some examples of this in my recent post here.

Dependency Injection

Changing property values is great for things like connecting to a different database server. But often in enterprise class applications you will need behavioral changes which are beyond simple property changes. One of the core features of the Spring Framework is the support of Dependency Injection. Once you become accustomed to development with Dependency Injection with in the Spring Framework, you will see how your code becomes more modular. Your classes will naturally adhere to the Single Responsibility Principle. If you’re doing Dependency Injection against Interfaces, it becomes very easy to swap out components.

Let’s say you have an application which needs to send a JMS message on an event such as a customer purchase. This may trigger an email to the customer about their order, and the data warehouse group might want the purchase information for their analytics. For your unit tests and your integration tests, you might be using Mockito to provide a mock. In your deployed environments you might be using the corporate standard of MQSeries for messaging. But what about doing CI builds? An embedded instance of ActiveMQ just might be perfect solution.

So, in summary, this example has:

  • A Mockito Mock object;
  • 3 different MQ Series configurations;
  • And embedded ActiveMQ.

The MQSeries configurations are easy to handle with property settings. The only thing changing here are the connection parameters. This is the perfect use case for externalized properties.

For your unit tests, if you want to keep them true unit tests (as I defined here), you’ll need to manage the dependency injection yourself. Testing frameworks such as Mocktio and Spock make this easy to do.

If you’re performing integration tests an easy way to manage the Spring Context is through configuration composition. But you may wish to favor using Spring Profiles instead. Each is easy to use, as I explain in the sections below.

Configuration Composition

Inexperienced Spring developers will place all their configuration into single xml files or configuration packages. This is often a mistake since it limits your configuration options. In our example, all of our configuration options could be supported through configuration composition. You would need to place each configuration into a separate xml file, or configuration package. Then selectivity import it into a parent configuration. You basically import the configuration you wish to use into a parent configuration, then load the parent into your Spring Context at run time. This is still a very popular technique to use for testing where it is very easy to specify the Spring context to use at runtime.

For a long time this was the only option Spring developers had to use. In Spring 3.1, Profiles were introduced to help manage different configurations. As you’ll see in the next section this a very powerful feature of Spring.

Spring Framework Profiles

Spring Profiles is a very powerful feature introduced in Spring Framework 3.1. Profiles allow you to define Spring Beans and specify when they should be loaded into the context.

If you do not mark your Spring Been with a profile, it will always be loaded into the Spring Context.

When you do mark your Spring Bean with a profile, then that profile must be set to active for that bean to be loaded into the Spring Context. This makes management of the environment easy, since you can simply mark the different options with the appropriate profile, then when you set that profile option to active, Spring will wire up the appropriate Spring Beans into your application.

There is one special profile that is rather poorly documented, but very nice to use. And that is the default profile. When you mark a Spring Bean using default , this bean is loaded into the context only if no other profile has been set to active. If it there is an active profile, Spring will attempt to find a bean matching that profile first.

What I like about using this option is you don’t have to set an active profile in production. While this is easy to use, from experience it can cause some friction and confusion with the configuration management team. Through the use of default profiles, your application can be deployed into production without an active profile being set.

Going back to the example we’ve been using, I would probably use a CI build profile for the CI build where I wanted to use an embedded instance of ActiveMQ, then setup the MQSeries option using the default profile. Having control over the CI build environment it’s easy for me to specify an active profile, so my CI build profile objects will get loaded into the Spring context. When my example application gets deployed elsewhere, no profile is set to active, so the default profile objects with the MQSeries configuration get loaded into the Spring Context. While we are supporting 3 different environments with MQSeries, this can be managed (and should be) with properties. This is because the MQSeries objects remain the same, except for the configuration of the environment the application is connecting to.

Conclusion

As an application developer, the Spring Framework offers you a lot of options on how you can compose your application. If you’re used to smaller scale development, the plethora of configuration options in the Spring Framework will probably seem like overkill to you. Why would you need such flexibility? Right? No, Wrong. As I’ve shown here, when developing applications in the enterprise you are going to be challenged with supporting the needs of many different environments. You are not just developing code on your laptop. No longer is the production environment the only environment you need to be concerned with. In a large enterprise you will need to support multiple environments, with different configurations and different needs. The Spring Framework has evolved over the years to support the challenging needs of enterprise application development. It’s no wonder that the Spring Framework is the most popular framework to use for developing enterprise class Java applications.

0
Share

Introduction

Spring 3 introduced the Spring Expression Language (SpEL) which has a syntax similar to Unified EL. It can save you a lot of coding, because you can dynamically assign values at runtime.

The folks at Spring, made the Spring Expression Language part of what is considered ‘Spring Core’. Thus, the Spring Expression Language is available for use throughout the Spring Framework.

Spring Framework Overview

SpEL can be configured through files and bean classes using XML and respectively Java annotation.

Spring Expression Language Examples

Project Setup

In this introductory course we will demonstrate how to use SpEL with XML and annotation based configuration to implement a simple example.

The @Component  annotation is used to register the component in Spring. Here are two components annotated correspondingly :

 

We run the application using the App class.

In the first step:
ConfigurableApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
we create an application context using ClassPathXmlApplicationContext which loads the configuration from bean file which is located in class path of the application.
Subsequent steps load the beans (in our case Employee and Company) from the context.
In the end: context.close() the ConfigurableApplicationContext.close() will close the application context, releasing all resources and also destroying all cached singleton beans.

where applicationContext.xml content is:

The applicationContext.xml can enable the auto component-scan to avoid bean declaration in XML file:

Once we created source and bean configuration files, let us run the application. The output will be:

Employee James Smith in Acme Company company and department Information Technology

Project Dependencies:

For a Maven project the pom.xml file is: