How to put in custom scope/context (JobScoped - custom CDI scope) particular instance from request to make it injectable?

前端 未结 3 1285
Happy的楠姐
Happy的楠姐 2021-02-03 13:59

Saying in a nutshell I would like to put in custom scope particular instance of Configuration class from rest request. Main problem is that custom scope (JobScoped from JBeret h

3条回答
  •  独厮守ぢ
    2021-02-03 14:43

    Firstly I would like to thank you again Jan-Willem Gmelig Meyling because your answer was very helpful. Anyway, I wanted to use given scope by JBeret which is JobScoped, today it could be only used on TYPE level. I did similary workaround as Jan-Willem Gmelig Meyling suggested but:

    • can use JobScoped
    • don't have to import extra libraries, everything works within CDI

    Solution:

    1) Configuration class:

    @JobScoped
    public class Configuration
    {...}
    

    2) At JobListener magic happens. Additional comments are redundant.

    Let's my code speak for itself ;)

    import javax.batch.api.listener.AbstractJobListener;
    
    public class MyJobListener extends AbstractJobListener{
    
        @Inject
        private Configuration jobScopedConfiguration;
    
    
        @Override
        public void beforeJob() throws Exception {
            enrichJobScopedConfigurationWithRequestConfiguration();
            ...
            super.beforeJob();
        }
    
        private void enrichJobScopedConfigurationWithRequestConfiguration(){
        Configuration requestConfiguration =
                    (Configuration) BatchRuntime.getJobOperator().getJobExecution(currentExecutionId).getJobParameters()
                            .get("configuration");
            jobScopedConfiguration.updateWith(requestConfiguration);
        }
    

    Now I can Inject my Configuration in any jberet/java batch artifact in context of job, e.g.:

    public class MyReader implements ItemReader {
    
    @Inject
    private Configuration configFile;
    }
    

提交回复
热议问题