0

I want to have an annotation where it will pull in a different config class based on the value of property. It might work something like this:

(All of this is pseudo code)

The annotation:

import org.springframework.context.annotation.Import;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Import(RedisConfig.class)
@Import(HazelCastConfig.class)
public @interface EnableCaching
{
    Class cacheType() default Redis.class;
}

An example of one of the configs:

import org.springframework.boot.autoconfigure.condition.ConditionalOnExpression;
import org.springframework.cache.annotation.EnableCaching;

import java.util.List;

@EnableCaching
@ConditionalOnExpression("#{T(com.mypackage.CacheAnnotationMatcher).checkCacheType(com.mypackage.Redis.class)}")
public class RedisConfig
{
    //...elided...
}

Where CacheAnnotationMatcher.checkProperty is a class and method I create that finds the @EnableCaching annotation and checks the cacheType property and returns true/false.

Don Rhummy
  • 24,730
  • 42
  • 175
  • 330

1 Answers1

0

I think you could use @ConditionalOnExpression here, I see absolutely no reason why your code wouldn't work, have your tried it?

helospark
  • 1,420
  • 9
  • 12
  • It doesn't allow passing the class. It throws an error. And the "*" doesn't work for allowing all packages. Is there a way to pass a yaml property? – Don Rhummy Nov 27 '17 at 21:06
  • You could pass a Class like: `...checkCacheType(Class.forName('com.something.Clazz'))`. Or pass it as a String, and compare the String representation of the class. I'm not entirely sure, what do you mean by passing yaml property. – helospark Nov 27 '17 at 21:09
  • Yes, I will pass it as a string if I have to, but I'd prefer to pass it as a class. – Don Rhummy Nov 27 '17 at 21:13