简体   繁体   English

Spring Bean-带参数的构造函数

[英]Spring Bean - Constructor with arguments

I see an error in the constructor which says 我在构造函数中看到一个错误,内容为

"String queueName" cannot be autowired. 不能自动连接“字符串queueName”。

I have AmazonSQSAsync component defined in another class but not queueName . 我在另一个类中定义了AmazonSQSAsync组件,但没有queueName Why is the constructor trying to autowire the parameters and how can I resolve this? 为什么构造函数试图自动装配参数,我该如何解决呢?

@Configuration
public class SqsQueueHealthIndicator extends AbstractHealthIndicator {

    private final AmazonSQSAsync amazonSQSAsync;
    private final String queueName;

    public SqsQueueHealthIndicator(AmazonSQSAsync amazonSQSAsync, String queueName) {
        this.amazonSQSAsync = amazonSQSAsync;
        this.queueName = queueName;
    }

    @Override
    protected void doHealthCheck(Health.Builder builder) {
        try {
            amazonSQSAsync.getQueueUrl(queueName);
            builder.up();
        } catch (QueueDoesNotExistException e) {
            builder.down(e);
        }
    }

    @Bean
    SqsQueueHealthIndicator queueHealthIndicator(@Autowired AmazonSQSAsync amazonSQSAsync, @Value("${url}") String queueName) {
        return new SqsQueueHealthIndicator(amazonSQSAsync, queueName);
    }

    @Bean
    SqsQueueHealthIndicator deadLetterQueueHealthIndicator(@Autowired AmazonSQSAsync amazonSQSAsync, @Value("${dlqurl}") String deadLetterQueueName) {
        return new SqsQueueHealthIndicator(amazonSQSAsync, deadLetterQueueName);
    }

}

Because you're declaring it as final so its value must be initialized. 因为您将其声明为final所以必须将其值初始化。

You did not provide default value so Spring understand its value will be injected. 您没有提供默认值,所以Spring知道将注入它的值。

So you have 2 options: 因此,您有2个选择:

  1. Remove the final modifier. 删除final修饰符。 Use @Value to inject your value from config file. 使用@Value从配置文件注入您的值。
  2. Create a bean type of String and inject it. 创建一个String类型的bean并将其注入。 You should name it: 您应该命名:

     @Bean("queueName") public String getQueueName {return "xyz";} 

And inject like: 并注入像:

    @Autowire
    @Qualifier("queueName")
    private final String queueName;

In normal circumstance, the option 1 is the go-to. 在正常情况下,选项1是首选。

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

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