1

I see an error in the constructor which says

"String queueName" cannot be autowired.

I have AmazonSQSAsync component defined in another class but not 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);
    }

}
2
  • Every field is autowired when you use the @Configuration annotation. Commented May 11, 2018 at 3:18
  • Is it true only for constructors? I tried @Component and I saw the same error. Commented May 11, 2018 at 3:19

1 Answer 1

6

Because you're declaring it as final so its value must be initialized.

You did not provide default value so Spring understand its value will be injected.

So you have 2 options:

  1. Remove the final modifier. Use @Value to inject your value from config file.
  2. Create a bean type of String and inject it. 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.

Sign up to request clarification or add additional context in comments.

1 Comment

String is not a primitive data type

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.