Constants and annotations

This might be a dumb question due to a lack of some understanding of java, but I have this code:

@Stateless @WebService public class MLHRequesterBean implements MLHRequesterBeanRemote { private final static String sel = "MLHRequesterPU" + (isProduction()? " " : "-dev"); public static boolean isProduction(){ try { if (Inet4Address.getLocalHost().getHostName().equalsIgnoreCase("ironman")) { return true; } } catch (UnknownHostException ex) {} return false; } @PersistenceContext(unitName=sel) ... 

Why is sel not considered a constant? We have a test server and a production server, and each of them should write to a different database. How can I solve this problem?

This is mistake:

C: \ projects \ workspace \ MLHRequester \ MLHRequester-ejb \ src \ java \ mlh \ MLHRequesterBean.java: 33: attribute value must be constant @PersistenceContext (UnitName = Selectivity) 1 error

+3
source share
4 answers

sel is the final static, but its value is evaluated the first time this class is loaded. @annotations are evaluated at compile time, hence the error.

You'd better do something like the macro / substitution preprocessing step during assembly to create the correct value (may be based on a .properties file).

+4
source

Constants are values ​​that can be fully resolved at compile time, your sel variable cannot be called up because it needs to query the local host name, so it cannot be evaluated until runtime.

0
source

sel is not a constant defined in JLS because it cannot be fully resolved at compile time. Annotations must be fully resolved at compile time, as they are baked in the class definition - they are not runtime properties (and this is their drawback).

To dynamically work with EJB at runtime, you will need to use EntityManagerFactory.

0
source

I would need to investigate if the initializer static block is executed before the annotations are resolved or not (i.e. solve the real problem), but you should use a static block for things like this:

 public class MLHRequesterBean implements MLHRequesterBeanRemote { private final static String sel; static { String suffix = (Inet4Address.getLocalHost().getHostName().equalsIgnoreCase("ironman")) ? " " : "dev"; sel = "MLHRequesterPU".concat(suffix); } } 
0
source

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


All Articles