Is there any difference between these two alternatives ... can they both be used interchangeably?
(A) Creating a custom annotation so @Inject can be used instead of @PersistenceContext within a DAO, as shown in the answer to - how-to-stack-custom-annotation-in-java-with-inject-annotation
(B) Using @Named("yourName") to qualify the Producer, such as the following code sample.
public class Resources {
/**
* EntityManager's persistence context is defined here so the @Inject annotation may be used in referencing classes.
*/
@Produces
@Named("MyEm")
@PersistenceContext(unitName = "jboss.managed")
private EntityManager em;
}
@Stateless
public class FiletracksentHome {
..
@Inject
@Named("MyEm")
private EntityManager entityManager;
..
}
They are interchangable, but you should use (A).
The @Named
annotation is primarily used for being able to access the object via expression language (EL), e.g. in a JSF view.
The problem is, that the resolution is done via String, thus being neither type safe, nor usually being automatically covered by refactorings in the IDE.
The CDI specification states that it should not be used for qualifying injection points if not be used to integrate legacy code.
Here's a nice article about this topic.