#Singleton #Startup depends on #Stateless EJB - java

I have the following setup:
#Singleton
#Startup
#DependsOn(value="DataSourceHandler")
public class TimerTask {
#EJB(name = "DataSourceHandler")
DataSourceHandler dataSourceHandler;
}
#Stateless(name = "DataSourceHandler")
public class DataSourceHandler {
... database operations
}
The timertask runs once every 30 minutes and performs database operations with the help of the DataSourceHandler EJB.
The problem here is that I'm unable to inject the EJB into the Singleton Timertask, because a singleton can only depend on other singletons. The solutions proposed in other questions don't work for me however:
I can't make the DataSourceHandler a Singleton because it is also used in other parts of the application and not multithreading-save.
I can't remove the Singleton from the TimerTask because it is required for the #Startup annotation
How can I inject a stateless into a singleton?

You do not need a dependsOn annoatation here.
#dependson is used for the below case:
Used to express an initialization dependency between singleton
components.
Since DataSourceHandler is an EJB, it will be instantiated by the container at the moment your singleton injects this EJB.

Related

Is #DependsOn necessary for another CDI bean that is injected?

Given two beans annotated with #Startup:
#Singleton
#Startup
#DependsOn("B")
public A {
#Inject
private B b;
}
#Singleton
#Startup
public B {}
Is #DependsOn neccessary in this situation to ensure that B is initialized before A? Or is there some convention over configuration that in such a situation the order of injections determines the order of initialization?
The official tutorial does not cover this case but only beans that are merely semantically covered without any syntactic/wiring link via #Inject.
If bean A actually depends on bean B being initialized then you need this.
With #Startup you are doing eager Instantiation - the singleton is instantiated at startup time whether or not it gets used.
In lazy instantiation, the singleton isn't instantiated until it's method's are first needed.
In both cases, container can initialize beans at whichever order it wants:
Sometimes multiple singleton session beans are used to initialize data for an application and therefore must be initialized in a specific order. In these cases, use the javax.ejb.DependsOn annotation to declare the startup dependencies of the singleton session bean.
Yes, it's necessary.
Otherwise nothing guarantees that B will be initialized before A.
According to the JavaEE 6 documentation:
Sometimes multiple singleton session beans are used to initialize data for an application and therefore must be initialized in a specific order. In these cases, use the javax.ejb.DependsOn annotation to declare the startup dependencies of the singleton session bean. The #DependsOn annotation’s value attribute is one or more strings that specify the name of the target singleton session bean. If more than one dependent singleton bean is specified in #DependsOn, the order in which they are listed is not necessarily the order in which the EJB container will initialize the target singleton session beans.
Example:
The following singleton session bean, PrimaryBean, should be started up first:
#Singleton
public class PrimaryBean { ... }
SecondaryBean depends on PrimaryBean:
#Singleton
#DependsOn("PrimaryBean")
public class SecondaryBean { ... }
This guarantees that the EJB container will initialize PrimaryBean before SecondaryBean.

best practices of using bean scopes in spring mvc application

I have seen it written at many places that DAO and Service classes of a spring application should be singleton scoped.
In my application I have the following service class
#Service
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerDAO customerDAO;
.......
parameterised methods only....
}
and a DAO class
#Repository
public class CustomerDAOImpl implements CustomerDAO {
#Autowired
private SessionFactory sessionFactory;
...............
parameterised methods only....
}
Since I haven't defined any scope, the default scope is singleton.So both the CustomerService and CustomerDAO will be instantiated only once per the container.Also the DAO class will be autowired to the Service class only once at the beginning.Since it is going to be a heavy request web application, that means (OR does that mean ?) hundreds of threads are going to use the same instances of both the classes.
Then how thread safety is guaranteed in this case ?
And what about the scope of hibernate sessionfactory bean defined in the xml ?
I am very much confused about the bean scopes and thread safety in a spring mvc application. Springsource documentation doesn't clearly explain these for a web application.
Could anyone please explain me the best practises of using bean scopes(for DAO, Service, Controller and other beans) for a heavy request web application ?
Any link which explains these woulb be grateful for me.
Thanks for your suggestions in advance.
As long as your service and DAO singletons do not hold state (don't hold instance variables - other beans excepted - manipulated inside methods), there is no problem regarding thread safety. Regarding session factory, the default hibernate session scope in spring web-app is based on the "one hibernate session per request" pattern, which means that you will have one session for each http request (thread) and so no reason to worry about concurrency neither.

Stateless ejb not getting destroyed

I have a REST interface for development purposes which sports a stateless EJB. It in turn injects another stateless EJB. It was my understanding that a stateless EJB is destroyed instead of passivated and reconstructed every time an instance is needed.
Using this logic I added a #PostConstruct (to both the REST and the other stateless ejb) but both are only called once (deduced from logging). Repeated calls to the REST layer will reuse the same bean (and its state!) instead of creating a new one.
What are the possible reasons that the stateless beans are not getting destroyed? Or have I misinterpreted the lifecycle of a stateless ejb?
EDIT: the "state" I'm referring to is a temporary cache the bean constructs to speed up execution. Perhaps a poor choice of words :)
EDIT2: some skeleton code:
import javax.ejb.Stateless;
import javax.ejb.EJB;
import javax.ws.rs.Path;
#Path("tools")
#Stateless
public class RESTTools {
#EJB
private CatalogueLocal catalogue;
#PostConstruct
public void initialize() {
logger.debug("Initializing REST client");
}
}
#Stateless
#Local(CatalogueLocal.class)
#TransactionManagement(TransactionManagementType.BEAN)
public class Catalogue {
#PostConstruct
public void initialize() {
logger.debug("Initializing catalogue");
}
}
I believe you have misinterpretted the lifecycle.
Stateless beans are instantiated as needed and are activated from an instance pool by the container.

Injection inside Quartz Job

I am using weblogic 11, ejb3.0
I am trying to do Ejb injection inside a class which implements Job (org.quartz.job)
No success.
So i Thought to make my job class as a stateless bean. like that:
#Stateless(mappedName = "StartSyncJob")
#Local(
{ StartSyncJob.class })
public class StartSyncJob implements Job
...
and then tried the Ejb injection inside again but I got exception:
blogic.ejb.container.compliance.ComplianceException: Business method notify in class java.lang.Object must not be declared as final
Guess I cant annotate a class which implements Job interface.
any other Idea how can I do it?
My main target is to call stateless bean which exists in another deployment from my Job class.
The container can only inject things created/managed by the container.
Quartz instantiates the job instances.
Hence the two don't play together as one framework.
You can create your own implementation of Quartz's JobFactory class to be in control of the instantiation of the job - and your implementation can delegate to something else, like the container.
Also, in your job, you can look up the Stateless bean yourself and then invoke it. Quartz ships with an EjbInvokerJob that does just that (invokes a configured ejb when it executes).

How is threadsafty guranteed with #PersistenceContext?

According to many examples it is possible to inject an EntityManager into #Stateless or #Singleton EJBs like this:
#Stateless // or #Singleton
public class MyRepository {
#PersistenceContext
private EntityManager em;
...
}
The EJB 3.1 Spec says that dependency injection is only performed at construction time, so that all callers of MyRepository would use the same instance of EntityManager. How does the EJB container ensure that the correct EntityManager instance is used?
My understanding is that a #Stateless bean will never be used by two clients concurrently; the container will simply create more instances of the same bean if it needs to serve multiple clients.
As for #Singleton beans, the spec says that by default they use Container Managed Concurrency, where the container uses method Locks and could reject clients with a timeout exception if the singleton is busy.
Edit: additionally, the #PersistentContext type is transaction-scoped by default (16.11.1.1 in the spec) so all entities managed by EntityManager are detached at the end of each transaction.

Categories

Resources