Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

create Bean in Spring through AsyncConfigurerSupport, respecting best practices with constructor

Tags:

java

spring

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

like image 233
George Lords of Castle Avatar asked Nov 28 '25 19:11

George Lords of Castle


1 Answers

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);
  }
}
like image 150
George Lords of Castle Avatar answered Nov 30 '25 08:11

George Lords of Castle



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!