Enum的String属性用于Annotation

时间:2011-02-10 17:58:03

标签: java annotations ejb

我想重用safetype enum,我已经为@Resource注释指定了需要String编译时常量的参数。 我没有找到任何优雅的解决方案如何重用DATASOURCE,除了我附上的内容:

public enum DATASOURCE {
  // Enum constants
  DataSource1, DataSource2;

  public final static String DataSource1_jndi = "java:/jdbc/DataSource1";
  public final static String DataSource2_jndi = "java:/jdbc/DataSource2";

  public String getJndiName() {
    switch(this) {
      case DataSource1:
        return DataSource1_jndi;
      case DataSource2:
        return DataSource2_jndi;
      default:
        throw new RuntimeException("Not defined jndi name for DATASOURCE " + this);
    }
  }
}

枚举本身的用法

public class DataSourceFactory {

  /**
   * @param ds Identifier of datasource
   */
  public static DataSource getDataSource(DATASOURCE ds) {
    // maybe some caching for datasource identified by constant
    ...
    return (DataSource) new InitialContext().lookup(ds.getJndiName());
  }
}

但是现在我想在SessionBeans中使用相同的DATASOURCE常量以及@Resource注释

@Stateless
public class SomeSessionBean {
  // This is what I would love to use but 
  // annotation wants compile time constant :-(
  // @Resource(mappedName=DATASOURCE.DataSource1.getJndiName());
  @Resource(mappedName=DATASOURCE.DataSource1_jndi);
  DataSource ds;

  ... 
}

有什么想法吗?

2 个答案:

答案 0 :(得分:0)

你的解决方案很好。

答案 1 :(得分:0)

你可以简单地说一下你的枚举:

public enum DATASOURCE {
Datasource1("java:/jdbc/DataSource1"), Datasource2("java:/jdbc/DataSource2");
private String jndiReference;

private DATASOURCE(String jndiReference) {
    this.jndiReference = jndiReference;
}

public String getJndiName() {
    return this.jndiReference;
}
}