Category Archives: Design

ThreadLocal usage

The ThreadLocal is very helpful to keep some information available from anywhere in the application but it is very important to release it when the process ends, otherwise, the resource will never be free and can cause a memory leak.

Here is an example of using TheadLocal to store data in a web application. I define a filter to setup the content of the ThreadLocal and I use it later in a servlet.

First of all, I create a class to store the ThreadLocal:

package net.classnotfound.threadlocal.handler;

public class ThreadLocalHandler {
    private static ThreadLocal myThreadLocal = new ThreadLocal<>();
    public static void setData(final String value) {
    public static String getValue() {
        return myThreadLocal.get();

    public static void remove() {

Now, the filter which is responsible of initialization of the ThreadLocal content:

package net.classnotfound.threadlocal.filter;


@WebFilter(urlPatterns = "*")
public class ThreadLocalFilter implements Filter {

    public void init(final FilterConfig filterConfig) throws ServletException {

    public void doFilter(final ServletRequest request, final ServletResponse response, final FilterChain chain) throws IOException, ServletException {
        long time = new Date().getTime();
        ThreadLocalHandler.setData("this is the value: "+time);
        chain.doFilter(request, response);


    public void destroy() {

Note that the Threadlocal is initialized before calling the next filter (via the filterChain) and released after.

Now, when I want to use the value, I just need to do:

String value = ThreadLocalHandler.getValue();

Access Spring context from web application

As I am using JSF with Spring, the beans managed by Spring are not accessible in my page, I used this Siegfried Bolz’s blog as a basis and used the facade pattern to hide access to the context.

The Spring context is loaded when the application starts using ContextLoaderListener in the apllication web.xml:


We need the following dependency:


Define the object which will reference the Spring context:

package net.classnotfound.spring.context;

import org.springframework.context.ApplicationContext;

public class AppContext {
    private static ApplicationContext ctx;

     * Injected from the class "ApplicationContextProvider" which is automatically
     * loaded during Spring-Initialization.
    public static void setApplicationContext(ApplicationContext applicationContext) {
        ctx = applicationContext;

     * Get access to the Spring ApplicationContext from everywhere in your Application.
     * @return
    public static ApplicationContext getApplicationContext() {
        return ctx;

Now, define the object that give you access to it:

package net.classnotfound.spring.context;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
 * This class provides an application-wide access to the 
 * Spring ApplicationContext! The ApplicationContext is 
 * injected in a static method of the class "AppContext". 
 * Use AppContext.getApplicationContext() to get access 
 * to all Spring Beans. 
 * @author Siegfried Bolz 
public class ApplicationContextProvider implements ApplicationContextAware {

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {



And now this is the facade object which gives access to the Spring beans:

package net.classnotfound.spring.context;

import org.springframework.context.ApplicationContext;

public class ServiceFacade {

	private static ServiceFacade instance = new ServiceFacade();
	private static ApplicationContext applicationContext;

	private ServiceFacade() {
		applicationContext = AppContext.getApplicationContext();

	public static ServiceFacade getInstance() {
		return instance;

	//Add here the method to get the different services available 
	// in the Spring Context
	public SpringBean getMyBean() {
		return (SpringBean) applicationContext.getBean("myBean");

Don’t forget to ask Spring to create the bean:

<bean id="contextApplicationContextProvider" 

To use it:

SpringBean bean = ServiceFacade.getInstance().getMyBean();



As I was working on the data access layer of my project, I noted that I have a lot of stuff to do to be able to access the Mapper from my web layer just for some simple CRUD actions.
Lot of stuff and even if I can detect some similarities, it’s not exactly the same, so I can’t just decide to put it in an interface or some abstract class, but lazy one day, lazy allways (it sounds better in french :D)…
After using my unique neurone to find solution, I finally arrive to a solution that I will present here.

To briefly describe my architecture, I have a web layer which access a service layer and then, the service layer can reach the data layer.
A requirement in my application is the user management (firstname, lastname, address, etc…), it’s what I will use to illustrate my solution.
First, I wanted to define a generic Dao to access my User object, to do that, the search all user is the simpler mechanism.
I need a simple POJO:

public class User {
    private Integer usrId;

    private String usrName;

    private String usrFname;

Now, the Dao, it will be responsible of accessing the MyBatis Mapper, and it will need to be able to manage all the Mapper, it’s why I defined a new interface which will contain the CRUD method:

public interface Mapper<T> {

    List<T> findAll();
    int insert(T record);
    T selectByPrimaryKey(Integer id);
    void updateByPrimaryKey(T object);
    void deleteByPrimaryKey(Integer id);


The MyBatis interface must now implement this interface specifying the User object:

public interface UserMapper extends Mapper<User>{

    int insert(User record);
    List<User> findAll();
    User selectByPrimaryKey(Integer userId);
    void updateByPrimaryKey(User user);
    void deleteByPrimaryKey(Integer usrId);

The Mapper is fine, it can be used by my Dao, in first, I define its interface:

public interface Dao {

    public List findAll();
    public T find(Integer id);
    public T merge(T obj);
    public void delete(T obj);

And the implementation which references the generic mapper I want to use:

public class DaoImpl implements Dao{

    protected Mapper mapper;

    public DaoImpl(Mapper mapper) {
        this.mapper = mapper;

    public List findAll() {
        return mapper.findAll();

there no problem to use the generic T because the real object is only known by the mapper “implementation”

And now the definition of my dao using Spring:

<bean id="userDao" class="net.classnotfound.dao.DaoImpl">
    <constructor-arg index="0" ref= "userMapper"/>

<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  <property name="mapperInterface" value="net.classnotfound.mapper.UserMapper" />
  <property name="sqlSessionFactory" ref="sqlSessionFactory" />

As you can see, the Dao is User agnostic, the Mapper is responsible of accessing the right objet. Now, ma Dao can be used with any Mapper, just by changing the Spring configuration.

But when we speak about CRUD, it’s not only getting the full list of records from the database, we need to be able to insert, update and delete, for that, you often need to add some data as the creation date or update date.
Usually, using JPA/Hibernate, I used a @PreUpdate or @PrePersist, but they are part of the JPA specifications, I cannot use it.
It’s why I decided to create some new interface to be able to acces to this particular fields.
For that, I defined 4 new interfaces, I will just present 2 of them but you can imagine the others:

public interface Identifiable {

    Integer getId();
    void setId(Integer id);
public interface Updatable {

    void setUpdateDate(Date date);

My user class must now implement these interfaces:

public class User implements Identifiable, Deletable, Updatable, Creatable

I can now add the update method in my DAO:

    public T merge(T obj) {
        if(!(obj instanceof Identifiable)) 
            throw new IllegalArgumentException("The object is not instance of Identifiable and cannot be updated!");
        Identifiable idable =  (Identifiable)obj;
        if (idable.getId()==null) {
            if (!(obj instanceof Creatable))
                throw new IllegalArgumentException("The object is not instance of Creatable and cannot be inserted!");
            Creatable creatable = (Creatable) obj;
            creatable.setCreationDate(new Date());
        } else {
            if (!(obj instanceof Updatable))
                throw new IllegalArgumentException("The object is not instance of Updatable and cannot be updated!");
            Updatable updtable = (Updatable) obj;
            updtable.setUpdateDate(new Date());
        return obj;

I need to cast the T object to be able to access to the related method.

When it is done for all the CRUD method, I have to use it in my service layer, the problem remains as I want to avoid the duplication of code.
It means that my service must be also

public interface Service<t> {
    List<t> findAll();
    T find(Integer id);
    T merge(T t);
    void delete(T t);
    void setDao(Dao<t> dao);
    Dao<t> getDao();

The service implementation looks like:

public class ServiceImpl<t> implements Service<t>{
    private Dao<t> dao;
    public List<t> findAll() {
        List<t> objects = dao.findAll();
        return objects;
    public T find(Integer id) {
        T user = dao.find(id);
        return user;
    public T merge(T object) {
        return object;
    public void setDao(Dao<t> dao) {
        this.dao = dao;
    public Dao<t> getDao() {
        return dao;

And the service declaration, in the Spring configuration:

    <bean id="userService" class="net.classnotfound.ServiceImpl">
        <property name="dao" ref="userDao"/>

In the same way as the Dao, my service in now Dao agnostic, I can create different services just using the Spring configuration, I will now have the time drink a coffee instead of repeating the same code in several classes 🙂