Say I have 2 service classes:
UserService
ProductService
Is it wrong if within my ProductService class I inject the UserService?
public class ProductserviceImpl implements ProductService {
#Autowired
UserService userService;
#Override
public void someThing() {
..
userService.otherThing(..);
..
}
}
I know as an alternative I could create yet another class that injects both UserService and ProductService, but coming up with a name for this class is very tricky :) Is there a name for these types of classes in the SOA world?
1) Is it wrong if within my ProductService class I inject the UserService?
There is nothing wrong with this per se, with the following caveats:
Be aware that you could be potentially heading in the direction of one class doing too much (here, the ProductService)
Be careful that you don’t introduce cyclic dependencies (you should not have UserService also depend on ProductService)
Limit tight coupling by wiring your dependency to the interface rather than the concrete class (here you are autowiring UserService instead of UserServiceImpl, which is good)
2) Is there a name for this type of class (that injects both UserService and ProductService) ?
Yes, as was mentioned, you could call this class a Mediator since the Mediator Pattern seems to describe this.
You can have both low-level services and high-level services, with the low-level ones (ProductService, UserService) injected into the high-level ones (say, PurchaseOrderService or PurchaseOrderMediator). Alternatively, for this particular case you might think of the product service as being a single high-level service that depends on UserService. At that point it’s more about which construct is more cohesive in the context of your business logic and your application.
For me, there's no problem to inject a service into another one. That's the point with services and SOA as you said.
Services can help each others in order to give you the final result. Besides, as told JB Nizet, if there is no cyclic dependencies, no problem.
What you are describing is called Mediator Pattern.
Btw what is SOA?
Injecting one service into another using spring like you have mentioned will couple, the 2 services only to the extent of the interface used.
If you need more decoupling, think of using a message to pass between the 2 services.
Message can be strongly typed like a value object/xml with schema
or weakly typed like a HashMap
While weakly typed messages can increase the decoupling, it means you and your client will forfeit compile time checking and debugging issues will be cumbersome at runtime
What you describe is object oriented integration and most likely not a SOA one. The fact that you may get (and should avoid) cyclic dependencies demonstrate that.
If you're services know other service Java level Interfaces you are also in a big risk to introduce tight coupling.
For instance, what's the return type from the User service? is it yet another interface that belong to the User service? do you pass it around in the code of product service?
Related
Sometimes Spring components may look like this:
#Service
public final class SomeService {
#Autowired
private SomeService2 someService2;
#Autowired
private SomeService3 someService3;
#Autowired
private SomeService4 someService4;
// … and many other services
#Autowired
private SomeDao someDao;
#Autowired
private SomeDao2 someDao2;
#Autowired
private SomeDao3 someDao3;
// … and many other DAOs
}
In other words Spring components have plenty services and DAOs that are mostly repeated in other Spring components. IMHO it has the following drawbacks:
Unnecessary (boilerplate) code for autowiring most of the same components
Sometimes Spring context loading error may occur due to circular references between components
What about to use all-in-one component that combine, say, all services or all DAOs. It will contain only links to Spring components with no any business logic inside:
#Service
public final class AllServices {
#Autowired
private SomeService2 someService2;
#Autowired
private SomeService3 someService3;
#Autowired
private SomeService4 someService4;
// … and many other services
// get methods to get some service
public someService getSomeService(){};
and inject it into other components:
#Service
public final class SomeService {
#Autowired
private AllServices serv;
#Autowired
private AllDaos daos;
#Autowired
private Environment env;
// inside some code
…
serv.getSomeService().processData();
IMHO it will look more succinct without circular references issues…
What pros and cons of this approach?
The second approach might look appealing, a well-known facade pattern comes to mind at first, so I can totally understand this.
However, I think the first pattern will work better in fact and here is why:
You say that the "all-mighty" service can solve circular dependencies
Well, circular dependencies usually point on a wrong / bad design and are code smell by there own, so hiding it behind a facade won't improve the system, resolving the circular dependencies will. In addition if from the actual services, called by "AllServices" you'll want to invoke additional service (again, bad design is preserved) then the code will probably pass through AllServices again, and hence the circular dependency is still there.
Using the second design assumes that this "AllServices" class will be used by all the components of the system, but in this case it becomes a "one-central-point" and refactoring in this class can turn to a madness - all the components / their tests might be affected
Initialization of this service can become a mess by itself, since you probably won't want to maintain a constructor that has 20-30 input parameters you'll resort to field injection (like in the example) which is bad by its own because if you want to initialize it somehow, probably from test, or something you want know what should be mocked and what not, in which order, and so forth.
Second approach may look cleaner, but it will be difficult to know which service is connected to service/DAO and therefore it will be hard to refactor or do/decide on which regression any change will cause. Meaning it effect software flexibility
This is the important difference which make the difference to choose first option IMHO
Maybe this is a question prone to be deleted, but just in case.
I've had a doubt lately while doing #EventListener annotated methods on my services if those methods should be included on the service's interface or not.
I mean, with a class like:
class FooServiceImpl implements FooService {
#EventListener
public void doSomethingWithEvent(ApplicationEvent event){
// do something
}
}
Should doSomethingWithEvent be included in FooService?
I think it shouldn't as the method is not meant to be directly invoked by any other instance but the one managing the events.
But, on the other hand, I would have a public method on my service that is not included on the interface, and for some reason, that smells bad to me (maybe it's just a habit).
So, what to do? Is there any convention regarding this?
I would say this is primarily opinion based, because afaik there is no real convention for this question. I didn't flag your question, because I think it is a good one and because I'm not sure if it is on or off topic.
Just ask yourself the following question: Is doSomethingWithEvent() part of my service? Is it part of the contract, its consumers (classes which use FooService) are using?
Or to break it down: Is there any case where a method, which uses FooService should be able to call doSomethingWithEvent() directly?
I don't think so.
So, with this in mind, basically: No, you shouldn't include that method in your interface. Programming against interfaces means you provide interfaces to your consumers and they can talk to them wihtout needing to know its implementations. That means also there could be (imho should be) different implementations for one interface. Some might provide an EventListener, some won't provide one.
I personally would prefer to create an own interface - let's say ApplicationEventAware and implement this in FooServiceImpl. You will find this approach in Spring many times. For this case I would name my implementation EventAwareFooService, and avoid *Impl classes, because this is bad design in my personal opinion. (and some might call it an anti pattern)
There is already ApplicationListener<E extends ApplicationEvent> So why not just implementing that?
I don't believe that there is a convention regarding this. However, I agree that doSomethingWithEvent() shouldn't be included in FooService. It will be interesting to see other peoples opinions on this.
I am new to spring MVC , I have downloaded a small spring MVC project . The project is executing fine but it this project interfaces and classes are being used .
like
public interface EmployeeService {
public void addEmployee(Employee employee);
public List listEmployeess();
public Employee getEmployee(int empid);
public void deleteEmployee(Employee employee);
}
And
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeDao employeeDao;
#Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public void addEmployee(Employee employee) {
employeeDao.addEmployee(employee);
}
public List listEmployeess() {
return employeeDao.listEmployeess();
}
public Employee getEmployee(int empid) {
return employeeDao.getEmployee(empid);
}
public void deleteEmployee(Employee employee) {
employeeDao.deleteEmployee(employee);
}
}
My doubt is if we are using EmployeeServiceImpl what is the need of implementing EmployeeService ? same thing is there in EmployeeDao and EmployeeDaoImpl.
Interfaces are always a good practice for decoupling, but also, when speaking about Spring, there are several features you can use having interfaces rather than concrete classes.
A big advantage is proxying - Spring AOP.
You can find more information here: http://docs.spring.io/spring/docs/3.0.x/spring-framework-reference/html/aop.html
There are other advantages, like post processing and things like that, but I think you will have an interesting reading on Spring AOP.
Weather spring mvc or not, one should always code to interface. Interface gives me better readability when i just want to see what the class does instead of worrying about how it does it, kind of API exposed to outer world.
Another benefit is there could be multiple implementations of 'how to do' it and spring helps to switch easily between multiple implementations. For e.g. you could have one more implementation of EmployeeService say FullTimeEmployeeServiceImpl, RemoteEmployeeServiceImpl.
Now if you have client class which uses EmployeeService:
class EmployeeManager{
private EmployeeService service;
}
you can inject any of bean here
<bean id="employeeManager" class="com.abc.EmployeeManager">
<property name="service" ref="fullTimeEmployee | remoteEmployee" >
</bean>
<bean id="fullTimeEmployee" class="com.abc.FullTimeEmployeeServiceImpl" />
<bean id="remoteEmployee" class="com.abc.RemoteEmployeeServiceImpl" />
A few principles that are part of the SOLID acronym for OO design apply to this:
Liskov substitution principle - you should be able substitute any subtype of T without affecting the outcome of the problem. E.g., if you call a method that returns a List<>, and the underlying implementation switches from returning an ArrayList<> to a LinkedList<>, your program should still perform in the same manner. Basically, you should design your classes so that client dependencies can be substituted with subclasses without the client knowing about the change. Here is a short snippet from the wiki page:
Substitutability is a principle in object-oriented programming. It
states that, in a computer program, if S is a subtype of T, then
objects of type T may be replaced with objects of type S (i.e.,
objects of type S may substitute objects of type T) without altering
any of the desirable properties of that program (correctness, task
performed, etc.)
Dependency inversion principle - The main idea is that you isolate the class behind a boundary based upon the abstractions it depends on. That way if any of the details that sit behind those abstractions change, the class will be unaffected.
In object-oriented programming, the dependency inversion principle
refers to a specific form of decoupling software modules. When
following this principle, the conventional dependency relationships
established from high-level, policy-setting modules to low-level,
dependency modules are inverted (i.e. reversed), thus rendering
high-level modules independent of the low-level module implementation
details. The principle states
A. High-level modules should not depend on low-level modules.
Both should depend on abstractions.
B. Abstractions should not depend on details.
Details should depend on abstractions.
It don't have much .to do with Spring or MVC.It is good practice to design with interfaces, so that implementation can be changes easily. It provides loose coupling and if you are using spring you can siimply change implementation. Whenver needed.
Also , it helps during testing with Junit. You can easily mockup your dao.
It is recommended to write code against interfaces instead specific implementations.
This way, the client code doesn't know the specific implementations but only knows the contract.
Regarding Spring, you generally have to use interfaces since Spring often needs to create Java proxies and this can be done only for classes that implement interfaces.
Sometimes, I find some class names including Aware such as ApplicationContextAware and MessageSourceAware (spring). Does this Aware have any special meanings or is it a famous rule?
Those are not classes, are interfaces. The name is just a convention on Spring meaning that some special framework object is going to be injected to that class if it is managed by the framework.
Directly from the docs of ApplicationContextAware:
Interface to be implemented by any object that wishes to be notified of the ApplicationContext that it runs in.
In this case, the bean that implements this interface will get a reference to the ApplicationContext managing the application.
Appending adjectives like "aware" to the end is a naming scheme often used for Java interfaces. This can then be implemented by classes, and the resulting is code which is more fluent to read for human beings, like
class Broker implements ApplicationContextAware { /* ... */ }
where it's quite easy to see that this class is a broker for something, and it knows how to deal with application contexts. Besides that, the "Aware" suffix has no special meaning from the Java (compiler) perspective.
The interfaces you cite seem to be a Spring-specific convention for allowing objects to interact with the dependency injection container that created them. By implementing the interface, a class signals that it wants certain information from the container and at the same time provides a method through which to pass that information.
I'd see it simply as an attempt to find a generic name for an interface that offers such functionality, not necessarily a strong convention with a specific technical meaning.
The concept of aware interfaces:
If I want the reference of objects of spring classes like XmlBeanFactory,ApplicationContext... In 2 or more classes, then there are 3 possible ways are there.
creating 2 BeanFactories in two classes.
creating at one class and sharing to all required classes .
In the 1st case ,we are unnecessarely creating 2 BeanFactories.
In the 2nd case, classes are tightly coupled with each other.
If our class implements BeanFactoryAware interface and overrides the contractual method called public BeanFactory setBeanFactory(BeanFactory factory) then IOC container see that special interface and calls setBeanFactory method by setting BeanFactory reference to that.
In 3. case above two problems are not there.
I want users to go through objectmanager for all persistence operation, instead of using UserDao directly, how can I make UserDao not visible to users. I am using spring to inject Implementation into UserDao.
public class ObjectManager {
public static UserDao USER_DAO;
#Inject
public void setUserDao(UserDao userDao) {
ObjectManager.USER_DAO = userDao;
}
}
public interface UserDao extends GenericDAO<User,Long>{
User findUserByUsername(String username);
}
what i am trying to achieve it that everyone follows one path to perform persistence operation, in my case it would be ObjectManager.USER_DAO.save(obj)..something like this instead of one developer doing userDao.save(obj)....the ObjectManger is purely for convenience. Any body can type objectManager. and the IDE will show a list of dao that are available
My advice: don't do this.
This would tightly couple your DAO classes to your central, static ObjectManager class for no obvious reason. This makes the code in your application hard to unit test, because static references like ObjectManager.USER_DAO.save(obj) can't be mocked. Also the application will be harder to maintain because any change to ObjectManager will hit nearly all your code (example future scenario: you want to move some DAO accessors out of the ObjectManager).
If you value testability and maintainability avoid global classes with static access.
It sounds like you want to add a layer between the persistence (DAO) layer and the service layer. I have a project where I do something similar, inserting a Repository layer.
When you have a layered application you can create a multi-module build and enforce dependencies between layers at build time. So the DAO layer is not on the compile-time classpath for the service layer.
You can make the Constructor private, Spring DI still will instantiate them using reflection.
Your users (programmers using your api/classes) can still instantiate classes if they use reflection too, however the normal use of "new MyClass()" will give you compile time errors. But the question remains, what do you want to achieve?
The normal way of achieving this is to change the UserDao scope to "package" level and let ObjectManager (assuming ObjectManager is part of the same package) act as a facade to it. Since UserDao is not accessible outside of the package no other client can instantiate it.
But since you are using Spring, I believe you can't do this. One work around I think of is to inject the UserDao with inner bean definition to ObjectManager. This way other code can't do a lookup using bean name or other cfg can't reference it.