Domanda

I've got a producer method that wants to produce a set that is unmodifiable:

// EnumSet.noneof returns an object of type Serializable, and also
// Collections#synchronizedSet javadoc says, "The returned set will be 
// serializable if the specified set is serializable."
private final Set<Role> roles =
      Collections.synchronizedSet(EnumSet.noneOf(Role.class));

...

@Produces @LoggedIn public Set<Role> getRoles()
{
    // Collections#unmodifiableSet javadoc also says, "The returned set will be
    // serializable if the specified set is serializable."
    return Collections.unmodifiableSet(this.roles);
}

I want to inject the set into a session scoped bean:

@Inject @LoggedIn Set<Role> roles;

At the injection point a warning is issued, saying that I cannot inject a set, which is not serializable, into a bean of passivating scope. The warning makes sense because the Set interfaces does not extend Serializable. However, in this circumstance it would appear, according to the javadoc, that roles is in fact serializable. I am not sure of the best way to handle this situation in order to avoid the warning.

Incidentally, I've noticed that applying @SuppressWarnings({"NonSerializableFieldInSerializableClass"}) at the injection point does not suppress the warning. But what I've also noticed that the following line of code in the same session scoped bean, located right next to the injection point, does NOT cause a warning message to be issued:

@Inject @LoggedIn Set<Role> roles;  // warning
private Set<Role> roles1;           // no warning!

Weird!

I have three questions:

  1. What would be the best approach to take in this circumstance?

  2. Why does @Inject @LoggedIn Set<Role> roles cause a warning whereas private Set<Role> roles1 does not?

  3. Why does applying @SuppressWarnings({"NonSerializableFieldInSerializableClass"}) at the injection point not suppress the warning?

È stato utile?

Soluzione

Only the first line is an injection point, hence CDI will scan it and ensure that it can be injected. The second line is not scanned by CDI to ensure that it's injectable, because CDI isn't trying to inject into it.

SuppressWarnings is a compile time annotation, not a runtime. It's lost in the compiled class.

You can create a Set implementation that implements serializable and use that. It should be injected as that set impl.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top