Enum String property used for annotation

I would like to reuse the safetype enumeration, which I should already specify an argument for @Resource annotation, which requires String compile time constant. I did not find an elegant solution how to reuse DATASOURCE, except that I am enclosing:

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); } } } 

Using the listing itself

 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()); } } 

But now I would like to use the same DATASOURCE constant also in SessionBeans along with the @Resource annotation

 @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; ... } 

Any idea?

+4
source share
2 answers

Your decision is in order.

0
source

You can simply list a little:

 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; } } 
0
source

Source: https://habr.com/ru/post/1339251/


All Articles