2011-07-28 55 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>