Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I have static public fields in my managed beans?

I just started using the Netbeans 7.1 beta and it is calling out errors of a type which I have never seen before. Specifically:

A managed bean with a public field should not declare any scope other than @Dependent.

The fields it is complaining about are public static final. I can understand the restriction on non-static fields, but I can't think of a good reason this would not be allowed for a static field. Unfortunately I use a lot of them since I don't like having constants in my code.

I note that even though I get the red dot in the margin in the editor, the maven-driven build still works and GlassFish still runs my application the way I would expect.

So what is my denoument on this issue? Am I going to have to move my static fields elsewhere or is there another way of handling this?

like image 489
AlanObject Avatar asked Nov 26 '11 01:11

AlanObject


2 Answers

Quoting the javax.enterprise.inject package javadocs:

If a managed bean has a public field, it must have scope @Dependent.

But I do agree wih @BalusC that if this compiles, Netbeans should report it as Warning (does it?).

Anyway, are those constants really part of the API? I mean, do you access they anywhere else but within their own classes? If not, reduce visibility to private. (If you just need to access the constants from the view you can also create accessors for the private constant). If yes, I would suggest you to move them somewhere else anyway.

like image 151
Anthony Accioly Avatar answered Oct 17 '22 04:10

Anthony Accioly


Public fields (static or not) aren't proxyable - that's why they can only be dependent scoped. To work around this you obviously can access them through getter methods.

like image 26
Jan Groth Avatar answered Oct 17 '22 03:10

Jan Groth