Java EE EJB injection in two coupled classes - java

I have the following classes:
public class ScoringService {
#Inject
public ServiceOne service1;
#Inject
public ServiceTwo service2;
#Inject
public DecisionHandler dh;
public void scoreData() {
Data d1 = service1.getData();
Data d2 = service2.getData();
Data newData = process(d1, d2)
dh.handle(newData);
}
}
public class DecisionHandler {
#Inject
public ServiceOne service1;
public void handle(Data newData) {
service.updateData(newData);
}
}
ServiceOne and ServiceTwo are #Stateless annotated EJBs.
I know that container makes pools for that Stateless EJB and also proxies for injections and stuff. So in my case is it possible that there will be two different instances of ServiceOne in both instances of ScoringService and DecisionHandler? And therefore there will be overgenerated ServiceOne instances? I mean the ScoringService with injected DecisionHandler in it will be called for one purpose and there is no need two hold two instances of ServiceOne.
I made the DecisionHandler a separate class to disassemble complex logic concentrated in one ServiceClass. Also I can make the DecisionHandler as a plain class with a method and instantiate it during call. How should I understand that I should make it an EJB?
I become to think that it some outdated stuff for only Client-Server model with thick cliend to help making calls to the servers EJBs through remote calls and it SHOULDN'T be used in projects with web or self-running computing programs. Is that true?

So in my case is it possible that there will be two different
instances of ServiceOne in both instances of ScoringService and
DecisionHandler?
if you are talking about #Stateless then it is up to the container (application server). You are not supposed to take any assumption on the number of EJBs serving clients. So you can have one or two, it is unpredictable.
I made the DecisionHandler a separate class to disassemble complex
logic concentrated in one ServiceClass. Also I can make the
DecisionHandler as a plain class with a method and instantiate it
during call. How should I understand that I should make it an EJB?
If your application server is JEE compliant (i.e. not Tomcat) and your application is middle/big sized and you need transaction, scalability, and you want a class to act as a stand alone component with specific business logic, then you probably need an EJB. Besides, have you tried to run your classes ? Because if they are not managed by the container, the #Inject is not working.
I become to think that it some outdated stuff for only Client-Server
model with thick cliend to help making calls to the servers EJBs
through remote calls and it SHOULDN'T be used in projects with web or
self-running computing programs. Is that true?
Unfortunately, most people think the current specification for EJB is still 2.x, while instead 3.x is out since 2009. EJB in their current specification are scalable, transactional...they have many benefits rather than disadvantages, and they fit perfectly in a web context.
However just because you have mentioned remote call: #Remote interface have a little overhead to think about and some design decision to be made (coarse grained vs fine grained interface).
[Update]
Regarding scalability, these are few fragments from the official EJB 3.1 specification, there are many more:
Just in the introduction
Applications written using the Enterprise JavaBeans architecture are
scalable, transactional, and multi-user secure.
Then...
A typical EJB container provides a scalable runtime environment to execute a large number of session objects concurrently.

Related

Local stateless EJBs vs Remote

I'm kind of a newbie in EJBs,but I've been given an EJB tier to improve.
This tier consists of an EJB wich exposes the operations available:
#Stateless(name = "myejb")
public class Facade implements FacadeRemote
{
#EJB
private EntityAHomeLocal entityAHome;
#EJB
private EntityBHomeLocal entityBHome;
// methods signatures and implementations
}
As you can see this EJB use other local EJBs that manage operations on entities.
#Stateless
public class EntityAHome implements EntityAHomeLocal
{
#PersistenceContext(name="myUnit")
private EntityManager manager;
// methods signatures and implementations
}
I'm having hard time to fully understand the architecture of this tier.
Is this kind of architrcture common ?
Are local stateless EJB managed throught a pool of instances just like remote stateless EJBs ?
Would it still work even if entityAHome and entityBHome were remote EJBs ?
Strictly speaking, the spec only says stateless beans are "typically" pooled (section 4.3.10.2), so the behaviour for local beans is vendor-specific, but in practice I believe all the major vendors do (for example).
Local and remote interfaces are almost entirely interchangeable, but with extra deployment restrictions (i.e. they must be deployed locally, of course), and some calls to local interfaces use pass-by-reference semantics, whereas remote interfaces always use pass-by-value (link).
I can't see anything that would stop that code working with remote interfaces, although I think some of the naming is confusing - a session bean (#Stateless) is different from an entity, and in EJB terminology "home" refers to a kind of factory class, which I don't think is your intention here (?). Also, be aware that switching to #Remote can add a performance overhead, as the second link notes.

Best way to not DRY the same private method in several EJBs?

I have some stateless EJBs and all of them have an equal private method:
private User getLoggedinUser() {
String username = sessionContext.getCallerPrincipal().getName();
return entityManager.createNamedQuery(User.findByUsername, User.class)
.setParameter("username", username).getSingleResult();
}
What is the best way to avoid this code duplication? Outsource getLoggedinUser() into a further bean and inject this in my existing EJBs?
As a rule the EJBs should be highly cohesive and for SOA architectures tends to work like Facades (Service Facades). So, this depends on EJB responsibilities. If is an EJB that has lots of helper methods you could extract them to a specialized Service (remember that CDI supports inheritance model, could be useful to group some helpers). I prefer to avoid pass on the entityManager across methods, mainly, because loads your methods with parameters (to less the better), at the end the persistence context is shared across all the EJBs and Services that works in the same transaction.
Another way is use an Interceptor, the idea is based on Decorator pattern, but Interceptors implies a little of magic, so, use it only if you want to accomplish a precondition or a cross cutting concern.

Advice wanted on a complex structure in java (DAO and Service Layer linking/coupling)

Introduction
I am trying to make a rather complex structure in Java with interfaces, abstract classes and generics. Having no experience with generics and only average experience with creating good OOP designs, this is beginning to prove quite a challenge.
I have some feeling that what I'm trying to do cannot actually be done, but that I could come close enough to it. I'll try to explain it as brief as I can. I'm just going to tell straight away that this structure will represent my DAO and service layers to access the database. Making this question more abstract would only make it more difficult.
My DAO layer is completely fine as it is. There is a generic DAO interface and for each entity, there is a DAO interface that extends the generic one and fills in the generic types. Then there's an abstract class that is extended by each DAO implementation, which in turn implement the corresponding interface. Confusing read for most probably, so here's the diagram showing the DAO for Products as an example:
Now for the service classes, I had a similar construction in mind. Most of the methods in a service class map to the DAO methods anyway. If you replace every "DAO" in the diagram above with "Service", you get the basis for my service layer. But there is one thing that I want to do, based on the following idea I have:
Every service class for an entity will at least access one DAO object, namely the DAO of the entity that it is designed for.
Which is...
The question/problem
If I could make a proper OO design to make each service class have one instance variable for the DAO object of their respective entity my service layer would be perfect, in my view. Advice on this is welcome, in case my design is not so good as it seemed.
I have implemented it like this:
Class AbstractService
public abstract class AbstractService<EntityDAO> {
EntityDAO entityDAO;
public AbstractService() {
entityDAO = makeEntityDAO(); //compiler/IDE warning: overridable method call in constructor
}
abstract EntityDAO makeEntityDAO();
}
Class ProductServiceImpl
public class ProductServiceImpl extends AbstractService<ProductDAOImpl> {
public ProductServiceImpl() {
super();
}
#Override
ProductDAOImpl makeEntityDAO() {
return new ProductDAOImpl();
}
}
The problem with this design is a compiler warning I don't like: it has an overridable method call in the constructor (see the comment). Now it is designed to be overridable, in fact I enforce it to make sure that each service class has a reference to the corresponding DAO. Is this the best thing I can do?
I have done my absolute best to include everything you might need and only what you need for this question. All I have to say now is, comments are welcome and extensive answers even more, thanks for taking your time to read.
Additional resources on StackOverflow
Understanding Service and DAO layers
DAO and Service layers (JPA/Hibernate + Spring)
Just a little note first: usually in an application organized in layers like Presentation / Service / DAO for example, you have the following rules:
Each layer knows only the layer immediately below.
It knows it only by it's interfaces, and not by it's implementation class.
This will provide easier testing, a better code encapsulation, and a sharper definition of the different layers (through interfaces that are easily identified as public API)
That said, there is a very common way to handle that kind of situation in a way that allow the most flexibility: dependency injection. And Spring is the industry standard implementation of dependency injection (and of a lot of other things)
The idea (in short) is that your service will know that it needs a IEntityDAO, and that someone will inject in it and implementation of the interface before actually using the service. That someone is called an IOC container (Inversion of Control container). It can be Spring, and what it does is usually described by an application configuration file and will be done at application startup.
Important Note: The concept is brilliant and powerful but dead simple stupid. You can also use the Inversion of Control architectural pattern without a framework with a very simple implementation consisting in a large static method "assembling" your application parts. But in an industrial context it's better to have a framework which will allow to inject other things like database connection, web service stub clients, JMS queues, etc...
Benefits:
Your have an easy time mocking and testing, as the only thing a class depends on is interfaces
You have a single file of a small set of XML files that describe the whole structure of your application, which is really handy when your application grows.
It's a very widely adopted standard and well - known by many java developers.
Sample java code:
public abstract class AbstractService<IEntityDAO> {
private IEntityDAO entityDAO; // you don't know the concrete implementation, maybe it's a mock for testing purpose
public AbstractService() {
}
protected EntityDAO getEntityDAO() { // only subclasses need this method
}
public void setEntityDAO(IEntityDAO dao) { // IOC container will call this method
this.entityDAO = dao;
}
}
And in spring configuration file, you will have something like that:
<bean id="ProductDAO" class="com.company.dao.ProductDAO" />
[...]
<bean id="ProductService" class="com.company.service.ProductService">
<property name="entityDAO" ref="ProductDAO"/>
</bean>

Why always have single implementation interfaces in service and dao layers?

I've worked/seen a few spring-hibernate web application projects having as many interfaces as there are actual service and dao classes.
I always thought that these two as the main reasons for having these single implementation interfaces:
Spring can wire actual implementation as dependencies in a given class (loose coupling)
public class Person {
#Autowired
private Address address;
#Autowired
private AccountDetail accountDetail;
public Person(Address address, AccountDetail accountDetail)
{ // constructor
While unit testing, I can create mock classes and test a class in isolation.
Address mockedAddress = mock(Address);
AccountDetail mockedAccountDetail = mock(AccountDetail);
Person underTestPerson = new Person(mockedAddress, mockedAccountDetail);
// unit test follows
But, of late, I realized that:
Spring can wire concrete implementation classes as dependencies:
public class Person {
#Autowired
private AddressImpl address;
#Autowired
private AccountDetailImpl accountDetail;
public Person(AddressImpl address, AccountDetailImpl accountDetail) {
// constructor
Mock frameworks like EasyMock can mock concrete classes as well
AddressImpl mockedAddress = mock(AddressImpl);
AccountDetailImpl mockedAccountDetail = mock(AccountDetailImpl);
Person underTestPerson = new Person(mockedAddress, mockedAccountDetail);
// unit test follows
Also, as per this discussion, I think the summary is that within a single app, interfaces are mostly overused probably out of convention or habit. They generally make best sense in cases where we are interfacing with another application for example slf4j used by many apps around the world. Within a single app, a class is almost as much an abstraction as an interface is.
So, my question is why do we still need Interfaces and then have single implementations like *ServiceImpl and *DaoImpl classes and unnecessarily increase our code base size. Is there some issue in mocking concrete classes that I’m not aware of.
Whenever I've discussed this with my team-mates, only answer I get is that implementing service and dao classes based on interfaces is THE DESIGN everybody follows - they mention about spring best practices, OOP, DDD etc. But I still don't get a pragmatic reason behind having so many interfaces within an isolated application.
There are more advantages to interfaces - As in proxying . If your class implements an interface , JDK dynamic proxies will be used by default for AOP . If you use the implementations directly, you'll be forced to use CGLIB proxies by making proxy-target-class=true . These require byte code manipulation unlike JDK proxies .
read here for more on this .
Read another discussion at what reasons are there to use interfaces (Java EE or Spring and JPA) for more info .
It's a very controversial subject. In brief, there's none—at least for you, the developer.
In EJB2 world, the Home and Remote interfaces were a must, and were exactly for a reason #AravindA mentions: proxies. Security, remoting, pooling, etc. all could be wrapped in a proxy, and provide the services requested strictly within standard library (as in DynamicProxy).
Now that we have javaassist and cglib, Spring (Hibernate, EJB3 if you prefer) are perfectly capable of instrumenting your classes as framework developer likes. Problem is, what they do is a very annoying thing: they usually request you to add a no-parameter constructor.—Wait, I had parameters here?—Nevermind, just add the constructor.
So interfaces are here to maintain your sanity. Still, it's strange, a no-argument constructor for a class with proper constructor is not something that makes a sense to me, right? Turns out (I should've read the spec, I know) that Spring creates a functional equivalent of an interface out of your class: an instance with no (or ignored) state and all the methods overridden. So you have a "real" instance, and a "fake interface" one, and what fake interface does is, it serves all the security/transactional/remoting magic for you. Nice, but hard to understand, and looks like a bug if you haven't taken it apart.
Moreover, if you happen to implement an interface in your class, (at least some versions of) Spring suddenly decides you were going to proxy this interface only, and the application just doesn't work for no apparent reason.
Thus, so far the reason is, safety and sanity. There are reasons why it is a good practice—but from your post, I see you already read all of those. The most important reason I can see today is the WTH/minute metric, especially if we're talking about newcomers to your project.

Java - Business Service, data access objects - Should Singletons be used or not?

Consider a web application with business layer and data access layer. So, every request has to be passed through these two layers in order to get processed.
Since there would be frequent requests coming in, it is not wise to create a new business and data access objects to process each and every request. In this case, usually I tend to go for Singletons of business and DAO.
But I hear lot of problems in using Singleton pattern, as many suggest against the pattern (mainly because its global). In that case, what would be the correct design strategy for the scenario I described above?
Service Objects should be Singleton.
You can use Spring to maintain singleton service objects for you.
The usual strategy used in such cases is to write the business services and data access objects not as singletons but as simple POJOs. And then use a container to manage the scope of the classes. Some examples of containers are Spring and Guice. You can even write your own container if your requirements are simple.
This way you get the benefits of the singleton pattern without its disadvantages (difficult to mock and test, etc).
A simple example:
public class PersonService {
public Person getPerson(String id) {
//find and return the person
}
}
public class PersonServiceSingletonFactory {
private PersonService service = new PersonService();
PersonService getInstance() {
return service;
}
}
I don't think that writing singletons on Servlet is good idea, you can create your business logic on ServletContextListener it will assure that only one instance of object will be run in container and it is thread-safe. you can access it the way #abhin4v explained. Unless you are using Spring framework this is what you need to do.
Hope it helps.

Categories

Resources