2011-07-28 53 views
5

是否有一些简单的方法将从类路径加载的Properties类加载到EJB(3.1)中?EJB3.1属性文件注入

事情是这样的:

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

谢谢

博佐

+1

不是那么简单容易标准的JavaEE。我怀疑CDI可以用@Inject + @ Produces做这样的事情,但我对CDI不够熟悉。 (留下这个评论,希望别人可以填写细节。) –

回答

3

正如bkail说,你可以通过以下方式实现这一目标。我不知道你loader=some.properties.loader的真正用意,所以跳过做什么用的,但如果提供的选项为您要使用loader.getClass().getResourceAsStream ("filename.properties");

首先定义你的注入式

@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 
@PropertiesResource(name = "filename.properties", loader = "") 
private Properties props; 

我没有这个寻找到其中@HttpParam被给定为一个例子here焊接文档。这是因为每个焊接1.1.0,在焊接1.0.0中,获得注释可以这样

PropertiesResource annotation = ip.getAnnotation(PropertiesResource.class); 
0

如果您正在使用的应用程序服务器具有WELD为CDI实现(Glassfish的3.x或JBoss的完成7.x或Weblogic的12例),那么你要使用焊接扩展其焊缝文档here

在解释这是因为添加以下内容到POM

<dependency> 
    <groupId>org.jboss.weld</groupId> 
    <artifactId>weld-extensions</artifactId> 
    <version>${weld.extensions.version}</version> 
    <type>pom</type> 
    <scope>import</scope> 
</dependency>