java 通过AsyncConfigurerSupport在Spring中创建Bean,遵守构造函数的最佳实践

tktrz96b  于 2023-03-11  发布在  Java
关注(0)|答案(1)|浏览(155)

我知道在Spring中创建@Service的最佳实践是将所有协作者作为最终字段,并在构造函数中包含@Autowired。我已经创建了一个类似的服务,需要通过AsyncConfigurerSupport实现将其示例初始化为Bean。
下面是将所有MyAsyncService协作者转换为最终字段之前的AsyncConfigurerSupport实现。

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();
  }
}

如何在将所有MyAsyncService协作者转换为final字段后将它们传递给构造函数?谢谢

l0oc07j2

l0oc07j21#

它可以通过ApplicationContext以这种方式完成。

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);
  }
}

相关问题