Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Sunday, August 16, 2015

Embedding ElasticSearch In a Spring Application

This blog post will show how to have ElasticSearch embedded in a Spring Application.

Motivation


Why Embed ElasticSearch in an application? Simple. To reduce the infrastructure overhead an application needs in other to run, making it more portable.

It is also for the same reason you will want to embed, say a web server, within your application.

It is especially appropriate to have ElasticSearch embedded when the use case does not require the distributed features of ElasticSearch and all that is needed is just a single node.


Saturday, November 15, 2014

Difference between BeanFactory and FactoryBean in Spring Framework

tl;dr A FactoryBean is an interface that you, as a developer, implements when writing factory classes and you want the object created by the factory to be managed as a bean by Spring, while a BeanFactory on the other hand, represents the Spring IoC container, it contains the managed beans and provides access to retrieving them. It is part of the core of the framework which implements the base functionality of an inversion of control container.

This post clarifies the difference between BeanFactory and FactoryBean in Spring Framework, and in the processes sheds some light on how the core component of Spring Frameworks stack together.

The Spring Framework has grown to be a lot of things, but at its core, it is a very versatile Dependency Injection container, upon which other things get built on. This core, this dependency injection container is actually built from 4 components.

1. The org.springframework.core package. In which, base functionalities that cut across the whole framework is implemented, e.g. exceptions, version detection etc.

2. The org.springframework.beans package. In which we have interfaces and classes for managing Java beans. The BeanFactory interface is found here.

3. The org.springframework.context Package. This builds on the beans package. An example of an interface out of this package that you would have used is the ApplicationContext (it implements the BeanFactory interface)

4. The org.springframework.expression package. This provides the expression language that can be used to traverse and manipulate the object graph within the container at runtime.


Tuesday, October 07, 2014

Injecting and Binding Objects to Spring MVC Controllers

I have written two previous posts on how to inject custom, non Spring specific objects into the request handling methods of a controller in Spring MVC. One was using HandlerMethodArgumentResolver
the other with @ModelAttribute.

An adventurous reader of these posts would have discovered, that even if you remove the implemented HandlerMethodArgumentResolver or the @ModelAttribute annotation the custom objects would still be instantiated and provided to the controller method!

Yes, try it!

The only problem is that the properties of the instantiated object would be null, that is they won't have been initialized (this won't be the case though, if these properties are instantiated in the default constructor).


Monday, October 06, 2014

Using Spring's Type Converter to Inject Objects into Spring MVC Controllers

The pattern of having the identity of a resource articulated in the URL is not uncommon; In fact it is one of the ways of expressing RESTful end points...for example in an application that displays details about people, you can have a URL expressed thus:

http://www.example.com/people/777

where 777 is the number that serves as the identifier used to fetch the resources, in this case that could be the corresponding Person Object with an identifier of 777.

It wont be taking it too far then, if we see the number 777, as a direct mapping to the Person object with an id of 777.

In fact the controller method that maps the the URL above may simply have logic that get's the 777 part of the URL and use it to fetch the corresponding entry in the database backing the application. for example:


Injecting Objects into Spring MVC Controller Using @ModelAttribute Annotation

In How to Inject Objects Into Spring MVC Controller Using HandlerMethodArgumentResolver, I showed how to implement the HandlerMethodArgumentResolver interface in other to have a custom object passed as a method argument of a Spring MVC controller.

This post looks at how to still pass objects into the Spring MVC controller, but using a some what different approach: The @ModelAttribute annotation.

The @ModelAttribute annotation can be used to designates operation that can both retrieve and put stuff into the model. Its functionality depends on where it is placed...two places actually: On controller methods and on controller's method arguments.

When @ModelAttribute is placed on a controller's method, it allows the putting of stuff into the Model and when on a controller method arguments, it allows retrieving stuff from the Model...

I thus, like to think of @ModelAttribute as an annotation driven mechanism for writing and reading from the Model.

This post would look at these two methods of using @ModelAttribute and how it can be used to inject objects into controller's methods.


Saturday, August 23, 2014

How to Inject Objects Into Spring MVC Controller Using HandlerMethodArgumentResolver


This post shows how to implement HandlerMethodArgumentResolver in other to resolve and inject objects into Spring MVC controllers, but before we get to the actual implementation procedure, a little trivial overview of Spring MVC would be good.

Spring MVC is designed around the Front Controller Pattern which it uses to implement the Model View Controller pattern.

Since you are reading this post, I can rightly assume you already use Spring MVC and you know how it generally works: You register the DispatcherServlet -Spring MVC's Front Controller, write your controller class and map requests to controller methods using @RequestMapping, then put the necessary configuration in place which would enable Spring to pick the written controller class and have it as a spring managed bean.

A trivial controller class may look like this:

package com.springapp.mvc;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;


@Controller
public class HelloController {


    @RequestMapping("/index")
    public String doGreeting(Model model) {
        model.addAttribute("greet", "Hello World");
        return "helloView";
    }
}

So when a request hits /index, doGreeting(...) method is invoked with an object of Model (the M in MVC) passed into it, which is populated with the greet property which can then be accessed in whatever view technology in used. The view is located using the "helloView" string returned by the controller.


Sunday, July 06, 2014

Hooking Into Container and Bean Life Cycle in Spring.

"What is the difference between BeanFactoryPostProcessor and BeanPostProcesser" This, said one of my colleagues, was part of his interview question, a question to which he promptly replied: "I don't know".

Once you pass the stage of actually getting Spring to work, passing the configuration huddle, in no time, the next couple of things you would probably run into would involve using or hooking into the various life-cycles in Spring and you start seeing things like BeanFactoryPostProcessor, BeanPostProcessor, DisposableBean, InitialzingBean, PostConstruct etc, which all seems to be callbacks mechanism that enables you plug in, somehow, into all the magic going on in Spring.

...And probably just like me, it all starts feeling like too much to grasp...Also, sooner or later, you run into the *Aware sets of interfaces too...

Dang! What are all these, How do they fit into the picture? I just want to write a web application, why do I have to grapple with all these what not?

I initially had all these concepts swirling all about without having any concrete mental model to attach them to or a good understanding of what actually is going on. I knew about the @PostConstruct annotation and maybe what it does, I also have come across various *Post Processors and maybe the IntializingBean interface a couple of times, but actually grokking and understanding where they fit did not happen until after spending some time working with other parts of Spring which allowed for a broader view of what is going, helping create some sort of mental model.


Monday, June 09, 2014

How to Autowire a Bean That Requires Constructor Argument In Spring

Spring allows you to inject a managed object (bean) as a dependency into another object via the @Autowired annotation.

For example, if I have a UserService that has a dependency on UserRepository, I can have the UserRepository injected using @Autowired annotation like this:

UserRepository Class...
class UserRepository {
UserRepository () {}
}


UserService Class...
class UserService {

@Autowired
private UserRepository userRepository;

UserService () {}

}

This is done using Field Injection. The same thing can be accomplied using Setter Injection:

class UserService {

private UserRepository userRepository;

UserService () {}

@Autowired // Using setter injection
public void setUserRepository(
UserRepository userRepository) {
this.userRepository = userRepository
}

}


or via Constructor Injection:

class UserService {

private UserRepository userRepository;

@Autowired // Using constructor Injection
UserService (UserRepository userRepository) {
this.userRepository = userRepository
}

}


There are different opinions on which method is "the right way" but since this post is not about that debate. I would point you to this post instead: Why I changed My Mind About Field Injection

Which ever method you choose to use, you are essentially doing the same thing: instructing Spring to supply an object's dependency by using the @Autowired annotation.

But what happens when the Object you want injected in has a constructor that requires an argument?


Friday, April 25, 2014

Configuring Aspect With Spring AOP

tl;dr Using AOP involves you identifying cross cutting concerns (Advice), extracting them out into a separate module and have them called at certain points in your code execution (Join Point) using certain expressions (Point-cut) to select these points where you want your cross cutting concern logic to run. Configuring thus involve telling Spring where your extracted logic is and the point-cut required to know where to apply them.

This post is part of the Configuring Spring Series.

Develop a sizable application and you would soon find yourself repeating some operations: certain logic; function calls that keeps recurring now and then. An example of such a recurring operation is logging. At different places, through out your application, you may find the need to have some information logged; either for debugging purposes or for auditing or for whatever reasons logging was invented. After a while you would soon find out that the log calls are sprinkled about the place in your code base. The drawback of having code scattered this way is even more if the code being repeated is not as trivial as log calls; Not good.

I have worked on a code base where this was the case. This is generally not advisable for various reasons: One, it fast become tedious having to repeat the same boring logic over and over again. Two, it leads to code entanglement as you have the flow of business logic being interrupted by mundane things that does not add to the business logic at hand. Third, it leads to code scattering. Same logic scatted all over the place. Even though the logic might be encapsulated into a method or function call, the method or function call would still be scattered all about the place. Not too good.

The explicitly of having to repeat these recurring calls might seem like a good thing, but with scale, it becomes not that much of a good thing.

Would it not be nice if it were possible to extract out, these recurring method calls, have it in some sort of separate module and then have it magically called when those operations that require them are reached during your code execution?

These kind of problems/situations is what Aspect Oriented Software Development seeks to solve/mitigate with Aspect Oriented Programming. It allows you to extract operations that cut across different aspect of your application and have them called when needed.

These kind of operations are usually called cross-cutting concerns, because, well they cut across various concerns in your application. :)

Apart from logging, operations that you would most likely run into, that can easily be classified as being cross-cutting concerns includes: Authorization, Error Handling, Performance Monitoring etc.

This post describes the process of configuring Spring framework in other to be able to use AOP in your application. As you might have guessed, the topic of Aspect Oriented Programming is a very broad one. And since these posts are mainly focused on configuration activities in Spring, I would not go into details of programming with Aspects; but instead explain basic concepts needed to get started and provide an overview of how AOP can be configured in Spring Application.

If you are familiar with event driven languages like Javascript (or any UI framework in most languages), you won't be totally wrong if you think the concept of Aspect sounds very familiar to what you do when you define functions as event handlers. And with event delegation, you can have this function registered to be executed when certain operations/event occurs within your application. The same reason why doing this makes sense also applies to why Aspects are recommended.

So let's get started with some of the basic concepts.


Friday, April 18, 2014

Configuring Spring Data JPA

tl;dr Spring Data JPA enables a Repository style of accessing data where the data source is a JPA powered data source. Configuration is simple. Have a working Spring JPA configuration, then add the Spring-Data-JPA as dependency to your project and enable the functionality by wiring the appropriate bean in your Spring Context.

Configuring Spring Data JPA is part of the Configuring Spring Series.

This short post would show how to easily configure Spring Data JPA for use and some related concepts that should help explain the rational behind Spring Data.

Spring Data JPA itself is part of a larger umbrella project: Spring Data. Which seeks to provides an easier, less broiler plate way to accessing data. A lot of the projects under the Spring Data use the Repository pattern, while some don't. Spring Data JPA is one of the projects that implements the Repository Pattern.

Since the Repository Pattern is central to Spring Data JPA, it is recommended to, at least, have an overview of what is going on when it is being used. After this, we go ahead to look at the configuration procedure, which is very succinct.

Repositories can be viewed as abstraction over data. This explanation, although partly correct, does not do justice to the unique identity of the Repository pattern. The question might be, if it is an abstraction over data, how is it then different from DAO's?

There are quite a lot of varied opinion regarding the difference between Repositories and Data Access Objects; but I like this answer to the question on Stackoverflow a lot.

Most specifically the part where it says:

DAO is an abstraction of data persistence. Repository is an abstraction of a collection of objects.

DAO would be considered closer to the database...Repository would be considered closer to the Domain, dealing only in Aggregate Roots. A Repository could be implemented using DAO's, but you wouldn't do the opposite...


This explanation also touches on some key concepts out of Domain Driven Design: Domain and Aggregate Roots. Understanding these also would help groking the essence of Repository pattern itself. Here is a nice blog post that talks about Aggregates and Aggregate Roots in Domain Driven Design. It is a post in a series. The other posts should shed more light on other parts of DDD.

For the more adventurous regarding the subject of DDD; the bible itself is a recommended read. If its 506 pages look intimidating, then maybe a less voluminous guide would be more appropriate: InfoQ Free eBook : Domain Driven Design Quickly. It is just 104 pages.

In short, as can be seen from the explanation of the difference between DAO Pattern and Repository Pattern; the Repository is a collection.

The developer using the Repository is not concerned about the source of the objects. The source could be a Database, a Network, File system, or a Web service. It does not matter. DAO on the other hand, more often than not, deals essentially with the Database.

It is worth nothing here that DAO actually stands for Data Access Object and not Database Access Object. It seems the pattern evolved to mean Database Access Object. :|

So with Spring Data JPA, you work with Repositories which returns to you, objects or collection of objects that are sourced from a JPA based data store.

So with this fact established. The actual configuration is trivial.

Since it is Data JPA, configuring it requires that you have a working JPA configuration in place. You can read Configuring Hibernate JPA in Spring Framework if your JPA provider would be Hibernate. The configuration procedure applies if other JPA provider is being used.

To add Spring Data JPA, you need to do two things. Add it as a dependency in your project (pom.xml in this example as Maven is used) and enable it by wiring the necessary bean in your Spring context.

In pom.xml add:


            org.springframework.data
            spring-data-jpa
            1.4.3.RELEASE


and in your Spring Context add:



jpa:repositories is a Spring xml namespace that serves as a short cut for explicit bean definition needed to get Spring Data JPA running. You can read the section on Hiding Bean Definition via Namespaces for more about this.

The base-package tells Spring JPA Data where to find interfaces it should use in implementing Repository objects for your application. Yes, Spring JPA Data looks for interfaces you specify and provides the actual needed implementation for use at start up. Cool right? This is another way Spring Data JPA makes data access easier with less code. For a more detailed explanation on this, read Working With Spring Data Repositories.

More materials on Spring Data JPA in general can be found on the project page on Spring.io

Sunday, April 13, 2014

Configuring Hibernate JPA in Spring Framework

tl;dr To configure JPA in Spring via Hibernate, you wire up one of the classes provided by Spring that creates a bean of type EntityManagerFactory which then makes EntityManager available for you. There are two types of Entity Managers, and the class you wire up depends on which Entity Manager factory you would be using. We have Application Managed and Container Managed Entity Managers.

This post gives an overview of how to configure Hibernate as a JPA implantation, for use in a Spring application. It is part of the Configuring Spring Series.


In Configuring Hibernate in Spring Framework, we saw that in other to talk to the database via Hibernate, your application code would do so via Spring's implementation of Hibernate's main interface: org.hibernate.Session which is made available via an implementation of  org.hibernate.SessionFactory. And the process of configuration is just a process of wiring up Spring's to provide this needed SessionFactory as a bean.

You have a similar procedure when it comes to configuring Hibernate JPA in Spring. 

Instead of working with a SessionFactory, you work with EntityManagerFactory. And instead of Hibernates' Session you have EntityManager  through which the actual database access is done.

The process of configuring Hibernate JPA in Spring hence, is all about wiring the Spring bean that would make available for you the EntityManagerFactory.

Before we get to the business of actual configuration, let's get some key concept's explained.


Monday, March 31, 2014

Configuring Hibernate in Spring Framework.

tl;dr to configure Hibernate in Spring, you need to configure a bean that implements org.hibernate.SessionFactory. Configuring this bean involves specifying the data source, the Object-to-Database mapping (if you using xml for the mapping) and the hibernate properties.

Last post in the Configuring Spring series looked into how to configure data sources, a basic requirement, regardless of the actual method in which your application would communicate with the database server: either via plain JDBC or via an ORM tool.

This post would look into how to configure Spring to use Hibernate. Hibernate is an object-relational mapping library for the Java language, that provides a framework for mapping an object-oriented domain model to a traditional relational database.

In how to configure data sources in Spring, we saw how the data source is the entry point to having your application communicate with a database server; how it is configured and retrieved for use in your application by classes that are specifically created to handle interaction with the database (DAO classes)

In configuring hibernate to work with Spring Framework, the data source still remains the primary entry point, but it would not be what your application code (or DAO class if you go with this pattern) would have to use directly in other to communicate with the database. With Hibernate, your application code requires something called the SessionFactory

So the process of configuring Spring to work with Hibernate is basically then all about configuration the bean that would make the SessionFactory available for you.


Sunday, March 30, 2014

Configuring Data Sources in Spring Framework

This is the second post in the configuring Spring series. It kickstarts the database centric configurations required when building an application that persist data with Spring framework. This post talks about configuring data sources.

There are various ways to enable the ability to persist data in your application. From using any of the available Implementation of Java Database Connectivity (commonly referred to as JDBC) to going the ORM route via any of the popular ORM frameworks (Hibernate, MyBatis, Eclipse Link etc )

But with any of the above mentioned method, a data source is always a requirement; because...well you need to have a source to the data if you want to persist and/or retrieve data. And in Spring the data source ends up as a Bean that you would configure.

Spring provides several options of configuring the data source. You can have:
  1. Data sources that are provided via JNDI.
  2. Data sources that work with JDBC drive.
  3. Data sources that are from a connection pool.
But before we go ahead to look at configuration proper, it would be useful to quickly define some basic concepts you would encounter when dealing with persistency:



Sunday, March 23, 2014

Configuring Beans in Spring Framework.

This is the first post in the Configuring Spring Series.

Beans in Spring framework are proxies implementation of your classes. And following the Inversion of Control way of doing things, they are managed by the Spring framework container and made available for you to use.

Meaning you basically write your classes like you would normally do when programming in Java. After which, you then need to go through a process of configuration that would guide Spring regarding how your classes would be transformed into managed beans which you can then use to form your business logic.

There are different ways to have this configuration set up. And this post, first in the series of many, that would cover some of the configuration tasks in Spring, covers how to configure Spring to take your classes and have it turned into beans. This process is normally referred to as Bean wiring.

We would look at
  1. Configuration via XML
  2. Configuration via Java Classes: JavaConfig
  3. Configuration via @Component and @Autowired Annotation


Configuring Spring Series

Configuring stuff can be overwhelming when you first start off with Spring framework. You spend an awful amount of time wiring things up and configuring before you actually get to start writing business code to solve the problem you are faced with...

Want to start using SpringMVC? there is a configuration for setting this up. Spring Security? There is a configuration for that. Want to use AOP, then you need to know how to have this configured. Want to access a database? You have to first wire up the datasource, the adapter etc etc

This can feel just too much.

It would fast became obvious to anyone using Spring that in other to get productive, configuration is something that is needed to be sorted out and have nicely filed away in a easily retrievable mental model so as to avoid losing precious time fighting the configurations or falling into configuration mishaps that could be a drag on productivity.

The posts that would follow under a series I called configuring spring is my attempt to do just that. It would be series of posts that covers some of the basic configuration hoop I have needed to jump over before I could get to actual development. And since I have a terrible, horrible memory, these posts would be a place I can also easily run to, to look up how a particular configuration needs to be wired.

This post would serve as an index and would be updated as I add to the series.

Posts so far:

1. Configuring Beans in Spring Framework
2. Configuring Data Sources in Spring for Database Access
3. Configuring Hibernate in Spring
4. Configuring Hibernate JPA in Spring Framework
5. Configuring Spring MVC
6. Configuring Spring Data JPA
7. Configuring Aspects with Spring AOP

Monday, September 16, 2013

Fixing org.springframework.http.converter.HttpMessageNotWritableException Error

A couple of days back, I ran into an interesting error while retrieving persisted entities as JSON  in SpringMVC:

[Request processing failed; nested exception is org.springframework.http.converter.HttpMessageNotWritableException: Could not write JSON: Infinite recursion (StackOverflowError)...


I had to do some poking around and reading up on documentation to figure out how to fix it.

As it turned out, the fix wasn't that complex and the culprit was Jackson: the Java-JSON processor being used to transform the retrieved Java entity to a JSON representation.

The error occurs when you try to retrieve an entity that has a bi-directional @OneToMany relationship with another entity.