gpt4 book ai didi

jakarta-ee - EJB3.1 属性文件注入(inject)

转载 作者:行者123 更新时间:2023-12-04 20:20:42 25 4
gpt4 key购买 nike

有没有一些简单的方法可以将加载了类路径中的文件的 Properties 类注入(inject) EJB(3.1)?

像这样的东西:

@Resource(name="filename.properties", loader=some.properties.loader)
private Properties someProperties;

谢谢,

博佐

最佳答案

正如 bkail 所说,您可以通过以下方式实现此目的。我不确定你的 loader=some.properties.loader真正的意思,所以跳过了做任何事情,但提供了选项,以防你想使用 loader.getClass().getResourceAsStream ("filename.properties"); 加载

首先定义你的注入(inject)类型

@BindingType
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.TYPE, ElementType.FIELD, ElementType.METHOD,
ElementType.PARAMETER })
public @interface PropertiesResource {

@Nonbinding
public String name();

@Nonbinding
public String loader();

}

然后为此创建一个生产者
public class PropertiesResourceLoader {

@Produces
@PropertiesResource(name = "", loader = "")
Properties loadProperties(InjectionPoint ip) {
System.out.println("-- called PropertiesResource loader");
PropertiesResource annotation = ip.getAnnotated().getAnnotation(
PropertiesResource.class);
String fileName = annotation.name();
String loader = annotation.loader();
Properties props = null;
// Load the properties from file
URL url = null;
url = Thread.currentThread().getContextClassLoader()
.getResource(fileName);
if (url != null) {
props = new Properties();
try {
props.load(url.openStream());
} catch (IOException e) {
e.printStackTrace();
}
}

return props;
}
}

然后将其注入(inject)您的命名组件。
@Inject
@PropertiesResource(name = "filename.properties", loader = "")
private Properties props;

我这样做是查看以@HttpParam 为例的焊接文档 here .这是根据weld 1.1.0,在weld 1.0.0中,获取注释可以这样完成
PropertiesResource annotation = ip.getAnnotation(PropertiesResource.class);

关于jakarta-ee - EJB3.1 属性文件注入(inject),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6855320/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com