spring自动连线和bean范围

siv3szwd  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(170)

考虑使用以下(简化)架构的spring webapp:
具有注解为@async的方法的服务:

@Service
public class MatriceAsyncFacade implements IMatriceAsyncFacade {

    @Resource
    private MatriceService myService;

    @Override
    @Async(MatriceFacadeAsyncConfig.MATRICE_EXECUTOR_NAME )
    public Future<MyClass> getMatriceFuture(Matrice matrice) throws TaskRejectedException {
            return new AsyncResult<>(this.myService.build(matrice));
    }
}

配置类:

@Configuration
@EnableAsync
public class MatriceFacadeAsyncConfig {

    public static final String MATRICE_EXECUTOR_NAME = "builderMatriceExecutor";

    @Resource
    private InitialisationDto initialisationDto;

    @Bean(name = MATRICE_EXECUTOR_NAME)
    // @Scope(WebApplicationContext.SCOPE_APPLICATION) // IMPORTANT_LINE_1
    public Executor threadPoolTaskExecutor() {
        final ThreadPoolTaskExecutor tpte = new ThreadPoolTaskExecutor();

        LOGGER.info("threadPoolTaskExecutor() corePoolSize={}", 
                         this.initialisationDto.getMatriceExecutorCorePoolSize());

        tpte.setCorePoolSize(this.initialisationDto.getMatriceExecutorCorePoolSize());

        return tpte;
    }
}

一个配置bean(initialisationdto),在application-context.xml中声明并首先由spring示例化

<bean id="initialisationDto" class="com.my.package.initialisation.InitialisationDto">
    <property name="matriceExecutorCorePoolSize" value="${matrice.executor.core.pool.size}" />
  </bean>

问题是:
在(本地)tomcat中部署webapp,效果很好(注意注解了@scope())
在我们的集成weblogic服务器中部署webapp时,必须添加@scope行,否则部署时会出现nullpointerexception:

Caused By: java.lang.NullPointerException
        at com.my.pacakge.config.MatriceFacadeAsyncConfig.threadPoolTaskExecutor(MatriceFacadeAsyncConfig.java:48)
        at com.my.pacakge.config.MatriceFacadeAsyncConfig$$EnhancerBySpringCGLIB$$615d2556.CGLIB$threadPoolTaskExecutor$0(<generated>)

npe从这条线升起:

tpte.setCorePoolSize(this.initialisationDto.getMatriceExecutorCorePoolSize());

在日志中,我可以首先看到webapp被初始化,initialisationdto被示例化和填充。紧接着,configurationclass中的bean被创建并显示日志“corepoolsize=…”。在那之后,我有了npe,就好像weblogic试图再次示例化这个bean,但是没有initialisationdto可用。
默认情况下,bean是单例的,那么为什么要在executorbean上添加@scope(webapplicationcontext.scope\u application)来解决这个问题呢?
注意:添加范围注解时,executor似乎是延迟示例化的,而不是在应用程序部署时。
版本:
java 8
Spring4.3.9.释放
weblogic 12.2版
汤姆猫9
tldr:weblogic部署中@async[singleton vs application\u scope]bean之间的实际差异?

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题