Java EE – which CDI scope should I use for Dao and service classes
I'm trying to build applications using JPA, CDI (open web beans delta spike JPA module), and JSF I use CDI deployed on Tomcat in the same way that I am used to using the spring framework I have a Dao called genericdaoimpl (the first few lines):
public abstract class GenericDaoJpa<T> implements GenericDao<T> { private static final Log logger = LogFactory.getLog(GenericDaoJpa.class); @Inject protected EntityManager entityManager; private Class<T> type;
Use deltaspike JPA module http://deltaspike.com apache. org/jpa. HTML injection into entitymanager This genericdao is then inherited by the concrete Dao used by the service class (userdao, etc.)
For example, userserviceimpl:
public class UserServiceImpl implements UserService { private static final Log logger = LogFactory.getLog(UserServiceImpl.class); @Inject private UserDao userDao; @Transactional public void saveUser(UserDto user) throws UserServiceException { try { User u = new User(user); userDao.create(u); } catch (Exception e) { logger.error("Error while creating user.",e); throw new UserServiceException("Error while creating user."); } } }
Using CDI in this way, both Dao and service classes will have a dependent scope, rather than a singleton like spring Therefore, each client will inject a new instance Should I change the scope of Dao and service classes to applicationscope? But according to the specification, I have to make all injected classes serializable In the case of Dao class, this may be a problem. Should entitymanager be marked as transient? One
I'd be happy to make any suggestions
Solution
@Applicationscope has nothing to do with serializable. They always exist and will never persist on disk @ sessionconcped will need to be serialized due to the behavior of the HTTP session object
I recommend using a scope because all dependencies cause memory leaks (it will never be clear when deleting @ dependent objects) If your application is fairly stateless, you can use @ requestscoped@ Applicationscope you need to consider multiple clients connecting to your instance