CDI(焊接 3.0.3.Final)如果@ApplicationScope,则不调用@PostConstruct



当我通过我的最新应用程序并致力于将豆子覆盖到@ApplicationScope时,我遇到了一个有趣的问题,因为我真的只需要 1 个实例。

我创建了几个类来从属性文件中注入值。 我像这样注射:

@Inject @Conf("key.in.properties.file")
protected String value;

@Conf注释很简单:

@Qualifier
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE, ElementType.FIELD, ElementType.METHOD, ElementType.PARAMETER})
public @interface Conf {
@Nonbinding
String value() default "";
}

我创建了一个具有@PostConstruct方法来加载属性文件的生产者类。 我已经确认在进行此@ApplicationScope时,不再调用@PostConstruct方法。 这不是延迟加载的问题。

@ApplicationScoped
public class ConfPropertyProducer {
private Properties props;
@PostConstruct
public void postConstruct(ConfDirectory confDirectory) {
props = new Properties();
try {
props.load(new FileInputStream(new File(confDirectory, "conf.properties")));
} catch (Throwable t) {
throw new RuntimeException(t);
}
}
@Produces
@Conf
public String produceStringProperty(InjectionPoint ip) {
Conf m = ip.getAnnotated().getAnnotation(Conf.class);
if (props == null) {
throw new RuntimeException("WHY IS PROPS NULL?");
}
return props.getProperty(m.value(), "-UNKNOWN-").trim();
}
} 

作为解决方法,我必须摆脱@PostConstruct方法并将其转换为类构造函数。

当没有任何@ApplicationScope,而是依赖于 CDI 的默认@Dependant范围时,它工作正常。 但我不确定为什么从不调用这个@PostConstruct方法。有人有什么想法吗?

您的@PostConstruct方法定义无效 - 您不能有任何参数。参见 javadoc。

你拥有它的方式意味着你以一种不确定的方式使用它。因此,很难猜测为什么它以一种方式工作而不是另一种方式工作,或者为什么它根本有效。而且可能根本不值得猜测。

注意 - 如果你需要在构造后调用之前做一些注入,那么最好的方法是用它进行构造函数注入。为了创建代理,您仍然需要一个无参数虚拟构造函数。

相关内容

  • 没有找到相关文章

最新更新