2011-07-28 6 views
5

クラスパスからEJB(3.1)にファイルをロードしたPropertiesクラスを簡単に挿入する方法はありますか?EJB3.1プロパティファイルの注入

このような何か:bkailでは、次の方法でこれを達成することができ、言ったように

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

は、

ボゾ

+1

ないあなたのPOMにこれを追加するのと同じくらい簡単です)例であり、標準のJavaEEです。私はCDIが@ Inject + @ Producesを使ってこのようなことをすることができると思っていますが、私はCDIに慣れていません。 (誰かが詳細を記入できるという希望でこのコメントを残す) –

答えて

3

、ありがとうございました。私は次に作成する、あなたのloader=some.properties.loaderが本当に何を意味するのかわからないようにして何もしてスキップされていますが、まず、あなたの注入型

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

    @Nonbinding 
    public String name(); 

    @Nonbinding 
    public String loader(); 

} 

を定義loader.getClass().getResourceAsStream ("filename.properties");

を使用してロードしたい場合には、そのためのオプションを提供しますそのプロデューサ

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として与えられている溶接のドキュメントを検討していました。これは、使用しているアプリケーションサーバーがCDIの実装(Glassfishの3.xまたはJBossのようWELDを持っている場合は、溶接1.0.0で、取得したアノテーションは、この

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

のように行うことができ、溶接1.1.0のとおりであります7.xまたはWeblogicの12、あなたはWELD溶接ドキュメントhere

に説明されて拡張子を使用することがでやすい

<dependency> 
    <groupId>org.jboss.weld</groupId> 
    <artifactId>weld-extensions</artifactId> 
    <version>${weld.extensions.version}</version> 
    <type>pom</type> 
    <scope>import</scope> 
</dependency> 
関連する問題