Home > Enterprise >  Autowire the configuration class into another configuration class field
Autowire the configuration class into another configuration class field

Time:06-03

I have a configuration class RetryConfig , which uses configuration properties of class RetryConfiguration.

In class RetryConfig , I am creating one object SimpleRetryPolicy field, which needs one property of class RetryConfiguration as below:

Ex:

public class RetryConfig {

//private static final int MAX_RETRY_ATTEMPTS = 5;

@Autowired
RetryConfiguration retryConfiguration;

private final SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy(retryConfiguration.getcount()); }

But with the above code, it fails.

whats i am missing here?

CodePudding user response:

Field initialization (SimpleRetryPolicy simpleRetryPolicy = new SimpleRetryPolicy...) happens before @Autowired is evaluated. Try one of those:

  • make SimpleRetryPolicy also a bean (e.g., @Component) and autowire RetryConfiguration there
  • create a constructor of RetryConfig with RetryConfiguration parameter and initialize simpleRetryPolicy in this constructor. The class then can look like this:
public class RetryConfig {

//private static final int MAX_RETRY_ATTEMPTS = 5;

RetryConfiguration retryConfiguration;
private final SimpleRetryPolicy simpleRetryPolicy;

@Autowired
public RetryConfig (RetryConfiguration c) {
simpleRetryPolicy = new SimpleRetryPolicy(c.getcount());}

 }
  • Related