How Can I use a Spring Variable Inside of an annotation?

Viewed 428

How can I get one of my spring configuration variables in an annotation that not inside of a class scope? Currently, I am doing this:

@Data
@RedisHash(value = "MyEntity", timeToLive = 604800 )
public class MyEntity{
    private String id;
    private String name;
}

but what I really want to do is this (or something equivalent):

@Data
@RedisHash(value = "MyEntity", timeToLive = @Value("${spring.redis.expire}") )
public class MyEntity{
    private String id;
    private String name;
}

Any solutions which allow me to access my config variables in my application.yml in my annotations (in this case, completing the value for my @RedisHash annotation)???

2 Answers

It turns out you can assign a configurable expiration value by using a @TimeToLive annotation inside of your @RedisHash annotated entity class. In my case, it looks like this:

@Data
@RedisHash(value = "MyEntity" )
public class MyEntity{
    private String id;
    private String name;

    @TimeToLive
    private Long expiration;
}

Then in the implementation that uses the redis entity, you simply assign that expiration value [myEntity.setExpiration(expiration);], as in the following code:

@Service
@RequiredArgsConstructor
@Slf4j
public class MyEntities {

    private final EntityRepository entityRepository;
    private boolean redisRepoIsHealthy = true;

    @Value("${spring.redis.expire}")
    private long expiration;

. . . . .
. . . . .
. . . . .
. . . . .

    private MyEntity saveEntityToRedisRepo(String userId, String name) {
        MyEntity myEntity = null;
        try {
                myEntity = new MyEntity();
                myEntity.setId(userId);
                myEntity.setAuthorities(name);
                myEntity.setExpiration(expiration);
                entityRepository.save(myEntity);
            }
        } catch (RuntimeException ex)  {
            // user is already saved in redis, so just swallow this failure
            if (redisRepoIsHealthy) {
                log.info("User {} already exists. Could not be saved.", userId);
                log.info("An error occurred ", ex);
            } else {
                log.info("The redis repo is corrupt. The user {} could not be saved.", userId);
            }
        }
        return myEntity;
    }

I guess this should work. Use property without @Value annotation.

@RedisHash(value = "MyEntity", timeToLive = "${spring.redis.expire}" )
public class MyEntity{
    private String id;
    private String name;
}
Related