【问题标题】:cdi bean injection for initialization code用于初始化代码的 cdi bean 注入
【发布时间】:2018-03-26 08:20:46
【问题描述】:

我配置了一个具有一些初始化逻辑的 bean。我已经使用 @ApplicationScoped 注释对这个 bean 进行了注释。但不知何故,cdi 没有选择这个 bean。

beans.xml 内容:

    <?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
    bean-discovery-mode="annotated">
</beans>

豆文件:

@ApplicationScoped
public class Initializer{

    @Inject @ConfigProperty(name = "app.name")
    private String appName;
    @Inject @ConfigProperty(name = "app.token")
    private String appToken;
    @Inject @ConfigProperty(name = "app.version")
    private String appVersion;

    @PostConstruct
    public void init() {
       System.out.println("flow should come here....); //but this line does not execute.
    }
}

读取配置文件的代码:

@Exclude
public class ConfigurationFile implements PropertyFileConfig {

    @Override
    public String getPropertyFileName() {
    String env = Util.getEnv();
    switch (env) {
    case "dev":
    case "uat":
    case "prod":
        return "config/" + env + "/default.properties";
    default:
        return "config/default.properties";
    }
    }

    @Override
    public boolean isOptional() {
    return false;
    }
}

我正在使用: cdiL:用于依赖注入, apache-deltaspike:用于读取配置文件。 wildfly-swarm:服务器

【问题讨论】:

  • 仅仅添加一个作用域并不能使它成为一个托管 bean。添加@Named注解
  • 我不确定 cdiL 是什么,所以很难评论问题可能是什么
  • 您实际上是否在以某种方式使用该 bean? Weld(您正在使用的 CDI impl)是延迟启动的,并且在需要之前不会创建实际的 bean,例如它不会调用 @PostConstruct - 在该 bean 上添加一些虚拟方法并尝试调用它。
  • 感谢您的意见。
  • 在 Kukeltje:这不对。 @Named 对于通过 EL 访问 bean 是可选的。

标签: cdi wildfly-swarm deltaspike


【解决方案1】:

我已经找到了解决这个问题的办法。

通过如下更改方法声明来解决问题:

public void init(@Observes @Initialized(ApplicationScoped.class) Object init) {
//................code logic here................
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-12-05
    • 2023-03-10
    • 2017-08-06
    • 2012-09-19
    • 1970-01-01
    • 2015-01-23
    • 2014-06-02
    • 1970-01-01
    相关资源
    最近更新 更多