I know that the best practice for creating a @Service in Spring to have all collaborators as final fields and to have the @Autowired in the constructor. I have created a service like that and I need to init an instance of it as a Bean through an AsyncConfigurerSupport implementation.
Here is my AsyncConfigurerSupport implementation before turning all MyAsyncService collaborators into final fields.
package com.my.spring.app.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class SpringConfig extends AsyncConfigurerSupport {
@Bean
public MyAsyncService createMyAsyncService() {
return new MyAsyncServiceImpl();
}
}
How to pass the collaborators to the constructor after turning all MyAsyncService them into final fields? Thanks
It can be done through ApplicationContext in this way.
package com.my.spring.app.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
@Configuration
@EnableAsync
public class SpringConfig extends AsyncConfigurerSupport {
private final ApplicationContext context;
@Autowired
public SpringConfig(ApplicationContext context) {
this.context = context;
}
@Bean
public AsyncSendingService asyncSendingService() {
return context.getBean(AsyncSendingServiceImpl.class);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With