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
Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
View Events Video Library
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Integrating PostgreSQL Databases with ANF: Join this workshop to learn how to create a PostgreSQL server using Instaclustr’s managed service

Mobile Database Essentials: Assess data needs, storage requirements, and more when leveraging databases for cloud and edge applications.

Monitoring and Observability for LLMs: Datadog and Google Cloud discuss how to achieve optimal AI model performance.

Automated Testing: The latest on architecture, TDD, and the benefits of AI and low-code tools.

Related

  • Embracing Reactive Programming With Spring WebFlux
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem
  • Comparing ModelMapper and MapStruct in Java: The Power of Automatic Mappers
  • A Guide to Enhanced Debugging and Record-Keeping

Trending

  • Understanding Europe's Cyber Resilience Act and What It Means for You
  • Implementing Stronger RBAC and Multitenancy in Kubernetes Using Istio
  • TypeScript: Useful Features
  • Decoding Business Source Licensing: A New Software Licensing Model
  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.

Ravi Isnab user avatar by
Ravi Isnab
·
Sep. 25, 18 · Tutorial
Like (7)
Save
Tweet
Share
19.85K 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, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Embracing Reactive Programming With Spring WebFlux
  • Spring Boot Annotations: Behind the Scenes and the Self-Invocation Problem
  • Comparing ModelMapper and MapStruct in Java: The Power of Automatic Mappers
  • A Guide to Enhanced Debugging and Record-Keeping

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends: