首页 > 解决方案 > jBeret + Weld SE - 从 Batchlet 注入托管 bean

问题描述

我正在尝试使 CDI 在 JBeret SE 上工作。这是我的代码:

SampleBatchlet 类

@Named
public class SampleBatchlet extends AbstractBatchlet
{
    @Inject
    @BatchProperty(name = "foo")
    String foo;

    @Inject
    StepContext stepContext;


    @Inject
    Logger logger;

    @Override
    public String process() throws Exception {
        final String say = stepContext.getProperties().getProperty("say");
        System.out.println("hello foolish");
        return null;
    }
}

SampleBatchletTest 类

@EnableWeld
class SampleBatchletTest {

    @Inject
    Logger logger;

    @WeldSetup
    public WeldInitiator weld = WeldInitiator
            .from(
                    LoggerProducer.class
            )
            .activate(
                    RequestScoped.class,
                    ApplicationScoped.class
            )
            .build();


    @Test
    void app() throws InterruptedException {

        final JobOperator jobOperator = BatchRuntime.getJobOperator();

        long id = jobOperator.start("simplebatchlet", null);

        final JobExecutionImpl jobExecution = (JobExecutionImpl) jobOperator.getJobExecution(id);
        jobExecution.awaitTermination(5, TimeUnit.SECONDS);
        Assertions.assertEquals(BatchStatus.COMPLETED, jobExecution.getBatchStatus());
    }

}

服务器类

@ApplicationScoped
public class Server {

    @Inject
    private Logger logger;

    public void init(@Observes @Initialized(ApplicationScoped.class) Object init) throws InterruptedException {
        logger.info("init");
}

LoggerProducer 类

public class LoggerProducer {
    @Produces
    public Logger produceLogger(InjectionPoint injectionPoint) {
        return LoggerFactory.getLogger(injectionPoint.getMember().getDeclaringClass().getName());
    }
}

问题是 Logger 实例未在 SampleBatchlet 上注入,而在上面的测试和服务器类中正确注入。

有什么提示吗?

小更新

通过阅读此参考资料

https://jberet.gitbooks.io/jberet-user-guide/content/batch_properties/

我发现 java.util.logging.Logger 可以被注入。

因此我添加了

<batchlet ref="it.infocert.shop.main.SampleBatchlet" >
    <properties>
        <property name="logger" value="java.util.logging.Logger" />
    </properties>
</batchlet>

价值实际上可以是任何东西..

在 SampleBatchlet 上我添加了

@Inject
@BatchProperty
Logger logger;

现在它被注入了。顺便说一句,我有点困惑,因为我希望使用另一个记录器实现..

标签: jsr352weld-sejberet

解决方案


我在我的 xml 上更改了 batchet ref:

  <batchlet ref="it.infocert.shop.main.SampleBatchlet">

至:

  <batchlet ref="sampleBatchlet">

现在它可以工作了


推荐阅读