繁体   English   中英

如何从 Spring Boot 中的活动配置文件中获取价值?

[英]How to get value from active profile in spring boot?

使用 spring boot 我在 .properties 文件中设置了值,并希望在我的服务类中使用该值。 有没有办法从活动配置文件中获取价值并在服务类中使用它?

这是我在.properties文件中的示例代码

    spring.rabbitmq.listener.simple.retry.enabled= true
    spring.rabbitmq.listener.simple.retry.initial-interval= 10s
    spring.rabbitmq.listener.simple.retry.max-attempts= 2
    spring.rabbitmq.listener.simple.retry.max-interval= 30s
    spring.rabbitmq.listener.simple.retry.multiplier= 2

我想在我的服务类中获得.max-attempts=2

这是我想要最大尝试值的服务类方法。

    public boolean validateRetryAttempts(EmailDto email)
        {

            @Value("${spring.profiles.active:unknown"
            int maxAttempt = 2;
            
            if (!maxRetryAttempts.containsKey(email.getEmail())) {
                maxRetryAttempts.put(email.getEmail(), 1);
                
            } else {
                
                if ((maxRetryAttempts.get(email.getEmail())+1)>=maxAttempt) {
                    maxRetryAttempts.put(email.getEmail(), maxRetryAttempts.get(email.getEmail())+1);
                    return true;
                } else
                    maxRetryAttempts.put(email.getEmail(), maxRetryAttempts.get(email.getEmail())+1);
            }
            
            return false;
            
        }

我在方法中尝试过@Value("${spring.profiles.active: unknown")但它给出了不允许的位置错误。

您不能将@Value放在方法中。 有效地点是:

  • 场地
  • 方法
  • 范围
  • 注解

写完后,请将其作为服务属性放置:

@Service
public class Service {

    @Value("${spring.rabbitmq.listener.simple.retry.max-attempts}")
    private int maxAttempt;

    public boolean validateRetryAttempts(EmailDto email){
  
        if (!maxRetryAttempts.containsKey(email.getEmail())) {
            maxRetryAttempts.put(email.getEmail(), 1);
        } else {
            
            if ((maxRetryAttempts.get(email.getEmail())+1)>=maxAttempt) {
                maxRetryAttempts.put(email.getEmail(), maxRetryAttempts.get(email.getEmail())+1);
                return true;
            } else
                maxRetryAttempts.put(email.getEmail(), maxRetryAttempts.get(email.getEmail())+1);
        }
        
        return false;  
    }

}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM