arinte
arinte

Reputation: 3728

Constants and annotation

This may be a silly question, due to missing 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 our test server and a production server and each one should write to a different DB. How can I overcome this issue?

This is the error:

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

Upvotes: 3

Views: 3695

Answers (4)

Droo
Droo

Reputation: 3205

I would have to research whether or not a static initializer block is executed before 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);
    }
}

Upvotes: 0

Yishai
Yishai

Reputation: 91881

sel is not a constant as defined in the JLS, because it can't be fully resolved at compile time. Annotations need to be fully resolved at compile time as they get baked into the class definition - they are not runtime properties (and this is their disadvantage).

To get this behavior with EJBs dynamically at runtime, you would have to use the EntityManagerFactory.

Upvotes: 0

luke
luke

Reputation: 14788

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

Upvotes: 0

Chii
Chii

Reputation: 14738

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

You are better off doing something like a macro/substitution pre-processing step during build to generate the right value (may be base it off a .properties file).

Upvotes: 4

Related Questions