DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Edge Computing's Infrastructure Problem: What Two Years of Factory Visits Actually Revealed
  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • Should You Use Azure Data Factory?

Trending

  • Java in a Container: Efficient Development and Deployment With Docker
  • The Death of "Text-Only" ChatOps: Why Google's A2UI Matters for DevOps and SRE
  • XMLSerializer - Removing Namespace & Schema Declarations xmlns:xsi xml:xsd
  • Designing Effective Meetings in Tech: From Time Wasters to Strategic Tools
  1. DZone
  2. Coding
  3. Frameworks
  4. Spring Generic Factory

Spring Generic Factory

Want to learn more about using the Spring generic factory types? Check out this tutorial where we look at how to create multiple objects using the generic type.

By 
Ravi Isnab user avatar
Ravi Isnab
·
Sep. 25, 18 · Tutorial
Likes (7)
Comment
Save
Tweet
Share
20.9K Views

Join the DZone community and get the full member experience.

Join For Free

Problem Statement

I want to be able to create multiple objects of the generic type without having to create each instance by hand and wire it in via@Bean.

In the code below, I am trying to create DefaultRedisClient and CacheReadService for the different class types: Person and Blog. That's just an example. In reality, there could be tens of classes/objects I would like to read from the cache, and for each one of those, I am duplicating the code with slight modifications.

To create this block of code again and again with only the CacheKey and CacheValue type changing along with a couple other things seems wrong.

@Configuration
public class RedisCacheReadServiceConfig  {

    @Bean
    public DefaultRedisClient< PersonCacheValue > personRedisClient(
            @Autowired @Lazy
            RedisTemplate< String, String > redisTemplate) {

        return new DefaultRedisClient<>(redisTemplate, PERSON.getName());
    }

    @Bean
    public CacheReadService< PersonCacheKey, PersonCacheValue > personCacheReadServiceRedisImpl(
            @Lazy @Autowired
            DefaultRedisClient< PersonCacheValue > personRedisClient,
            @Lazy @Autowired
            PersonCacheFallback personCacheFallback,
            @Lazy @Autowired
            RedisClientFactory< PersonCacheValue > redisClientFactory) {

        return new DefaultCacheReadService<>(personRedisClient, PERSON, personCacheFallback);
    }

    @Bean
    public DefaultRedisClient< BlogCacheValue > blogRedisClient(
            @Autowired @Lazy
            RedisTemplate< String, String > redisTemplate) {

        return new DefaultRedisClient<>(redisTemplate, BLOG.getName());
    }

    @Bean
    public CacheReadService<
            BlogCacheKey,
            BlogCacheValue > blogCacheReadServiceRedisImpl(
            @Lazy @Autowired
            DefaultRedisClient< BlogCacheValue > blogRedisClient,
            @Lazy @Autowired
            BlogCacheFallback blogCacheFallback,
            @Lazy @Autowired
            RedisClientFactory< BlogCacheValue > redisClientFactory) {

        return new DefaultCacheReadService<>(blogRedisClient, BLOG, blogCacheFallback);
    }
}


Solution

The fact of the matter is that there's a better way. Since Spring 4.0, Spring will automatically consider generics as a form of @Qualifier. And because of that, we can have a factory pattern that uses generic types, such as @Qualifier. Please consider the example below:

/**
 * A factory that generates / provides DefaultRedisClient < V >
 *
 * @param  CacheValue type
 */
@Service
public class RedisClientFactory< V extends CacheValue > {

    private final RedisTemplate< String, String > redisTemplate;

    @Autowired
    public RedisClientFactory(@Lazy RedisTemplate< String, String > redisTemplate) {

        this.redisTemplate = redisTemplate;
    }

    public DefaultRedisClient< V > getRedisClient(final String domainName) {

        return new DefaultRedisClient<>(redisTemplate, domainName);
    }
}


With the RedisClientFactory above, our main config becomes simpler because instead of creating DefaultRedisClient beans for different CacheValue types, we have delegated that work to the RedisClientFactory and now can simply auto-wire DefaultRedisClient<V> by specifying the generic class type V. See line number 7 and 19 below. Spring is injecting a generic RedisClientFactory of the given type. Once we have that, we can simply call the getRedisClient method to create the RedisClient we want.

@Configuration
public class RedisCacheReadServiceConfig  {

    @Bean
    public CacheReadService< PersonCacheKey, PersonCacheValue > personCacheReadServiceRedisImpl(
            @Lazy @Autowired
            PersonCacheFallback personCacheFallback,
            @Lazy @Autowired
            RedisClientFactory< PersonCacheValue > redisClientFactory) {

        return new DefaultCacheReadService<>(redisClientFactory.getRedisClient(PERSON.getName()), BLOG, personCacheFallback);
    }

    @Bean
    public CacheReadService < BlogCacheKey, BlogCacheValue > blogCacheReadServiceRedisImpl(
            @Lazy @Autowired
            BlogCacheFallback blogCacheFallback,
            @Lazy @Autowired
            RedisClientFactory< BlogCacheValue > redisClientFactory) {

        return new DefaultCacheReadService<>(redisClientFactory.getRedisClient(BLOG.getName()), BLOG, blogCacheFallback);
    }
}


But, we can go one step further and create a factory class to create CacheReadService for different CacheKey and CacheValue. See below:

  • In line 9, we are injecting the genericRedisClientFactory<V>

  • In line 19, we use the generic RedisClientFactory<V> to create a generic DefaultRedisClient<V>.

  • In line 20, it is a pretty straightforward creation of CacheReadService<K,V>.

@Service
public class CacheReadServiceFactory< K extends CacheKey, V extends CacheValue > {

  private final RedisClientFactory redisClientFactory;
  private final CacheFallback cacheFallback;

  @Autowired
  public CacheReadServiceFactory(
    @Lazy RedisClientFactory< V > redisClientFactory,
    @Lazy final CacheFallback< K, V > cacheFallback) {

    this.redisClientFactory = redisClientFactory;
    this.cacheFallback = cacheFallback;
  }

  public CacheReadService< K, V > getCacheReadService(
    final CacheDomainType cacheDomainType) {

    final DefaultRedisClient< V > redisClient = redisClientFactory.getRedisClient(cacheDomainType.getName());
    return new DefaultCacheReadService<>(redisClient, cacheDomainType, cacheFallback);
  }
}


Now, because of the CacheReadServiceFactory (above), our configuration class (below) becomes super simple because of Spring and being able to use generics for auto-wiring (since Spring 4.x).

Final Solution

/**
 * Final Config class
 */
@Configuration
public class RedisCacheReadServiceConfig {

  @Bean
  public personCacheReadService(
    @Lazy @Autowired
    final CacheReadServiceFactory< PersonCacheKey, PersonCacheValue > cacheReadServiceFactory
  ) {

    return cacheReadServiceFactory.getCacheReadService(PERSON);
  }

  @Bean
  public blogCacheReadService(
    @Lazy @Autowired
    final CacheReadServiceFactory< BlogCacheKey, BlogCacheValue > cacheReadServiceFactory
  ) {

    return cacheReadServiceFactory.getCacheReadService(BLOG);
  }
}


Please feel free to leave questions or comments below!

References

1: https://spring.io/blog/2013/12/03/spring-framework-4-0-and-java-generics

Spring Framework Factory (object-oriented programming)

Published at DZone with permission of Ravi Isnab. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Enabling Behavior-Driven Service Discovery: A Lightweight Approach to Augment Java Factory Design Pattern
  • Edge Computing's Infrastructure Problem: What Two Years of Factory Visits Actually Revealed
  • Building a CRUD Application With Spring and SimpleJdbcMapper
  • Should You Use Azure Data Factory?

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook