【问题标题】:How Can I use a Spring Variable Inside of an annotation?如何在注释中使用 Spring 变量?
【发布时间】:2021-10-22 06:26:36
【问题描述】:

如何在不在类范围内的注释中获取我的 spring 配置变量之一?目前,我正在这样做:

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

但我真正想做的是这个(或类似的东西):

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

任何允许我在我的注释中访问我的 application.yml 中的配置变量的解决方案(在这种情况下,完成我的 @RedisHash 注释的值)???

【问题讨论】:

  • 行不通。除非语言发生了变化,否则注释是在编译时设置的,而不是运行时。
  • @Ryan 是否有任何其他策略可以将此编译时间变量放入编译时间注释中?

标签: java spring redis annotations


【解决方案1】:

事实证明,您可以通过在 @RedisHash 带注释的实体类中使用 @TimeToLive 注释来分配可配置的到期值。就我而言,它看起来像这样:

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

    @TimeToLive
    private Long expiration;
}

然后在使用 redis 实体的实现中,您只需分配过期值 [myEntity.setExpiration(expiration);],如下代码所示:

@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;
    }

【讨论】:

    【解决方案2】:

    我想这应该可行。使用不带@Value 注释的属性。

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

    【讨论】:

      猜你喜欢
      • 2018-06-26
      • 1970-01-01
      • 2019-09-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多