I have a spring MVC application. Each controller of the application auto-wires the #Service components it needs to interact with. A Sonarqube analysis has detected that there was some duplication in this: some controllers may use the same services, in which case the #Autowired annotation and the corresponding fields are indeed the same.
For instance, the following would be duplicated in many controllers:
#Autowired
private FooService fooService;
#Autowired
private BarService barService;
This is a minor issue, and I don't know whether/how I should address this. Since all my controllers inherit an AbstractController, and all services are singletons, would it make sense to put all #Autowired elements in the base class, in protected fields?
If the dependencies already are in the subclasses, you probably have a reason for that, e.g. they do not conceptually belong in the abstract class. Keep them in the subclass if so.
It's important to adhere to the DRY principle, but don't be fanatic about it. Duplicating code gives you flexibility, and class dependencies are a typical place where you want such flexibility. Not to mention that the code is simpler with such duplication.
Static code analysis is good for providing pointers to improve your code, but they shouldn't be followed blindly.
Related
Can the specialised variants of Spring's #Component be inappropriately used? i.e. if I call my service class #Repository instead of #Service or the reverse.
Is there any safeguards against such inappropriate use or is it just a recommendation that they be used correctly as per context without any enforcement from Spring?
Could some one please let me know what exactly happens with each Stereotype?I read the javadocs and don't fully understand what specialised set of features does each of Spring Stereotype offers
Yes, you can annotate any class with #Repository or #Service, and both of them will behave the same but here comes the interesting point from documentation:
Therefore, you can annotate your component classes with #Component, but by annotating them with #Repository, #Service, or #Controller instead, your classes are more properly suited for processing by tools or associating with aspects. For example, these stereotype annotations make ideal targets for pointcuts.
Thus, if you are choosing between using #Component or #Service for
your service layer, #Service is clearly the better choice. Similarly,
as stated above, #Repository is already supported as a marker for
automatic exception translation in your persistence layer.
Here you can see two important things being discussed Ideal target for pointcuts in the first para and 2nd one as automatic exception translation
Clearly, 1st one is understandable if you are aware of AOP and second one is one beautiful thing about these annotations. Lets see the docs what does automatic exception translation mean:
Common data access exceptions. Spring can wrap exceptions from your O/R mapping tool of choice, converting them from proprietary (potentially checked) exceptions to a common runtime DataAccessException hierarchy. This allows you to handle most persistence exceptions, which are non-recoverable, only in the appropriate layers, without annoying boilerplate catches/throws, and exception declarations. You can still trap and handle exceptions anywhere you need to. Remember that JDBC exceptions (including DB specific dialects) are also converted to the same hierarchy, meaning that you can perform some operations with JDBC within a consistent programming model.
So basically, they are same, but they differ a little when you dig deep. Hope you got it.
for example, if we annotate all the classes with #Service annotation, all of these classes will be registered in the container but how things will differ. See, if you annotate some class with #Repository annotation, the postprocessor automatically looks for all exception translators (implementations of the PersistenceExceptionTranslator interface) and advises all beans marked with the #Repository annotation so that the discovered translators can intercept and apply the appropriate translation on the thrown exceptions.
So, again, it is all about some sort of exception handling. Now, if you annotate the class with #Service annotation rather than #Repository annotation, the required translators will not get discovered.
Now regarding #Service annotation. This annotation doesn't bring more to the table than #Component. They are same, the only difference is #Service annotation is a specialization of #Component , and the only specialization it adds according to the docs is
This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use as appropriate.
Hence, #Service just adds more understanding than #Component.
So, at the end, we came to know that all are nearly same with slight differences where #Repository annotations has some more benefits in case of DAO class.
This question already has answers here:
What is dependency injection?
(37 answers)
Closed 7 years ago.
I have a class
#Component
public class MessageServiceHelper {
#Autowired
private MessageService messageService;
public boolean sendMessage(String text){
return messageService.sendMessage(text);
}
public MessageService getMessageService() {
return messageService;
}
public void setMessageService(MessageService messageService) {
this.messageService = messageService;
}
}
so here I am autowiring messageService, so that whenever the object ob MessageServiceHelper is instantiated then it will automatically inject dependency messageService into MessageServiceHelper. Same thing I can achieve if I have write some other class which will create the instance of MessageService and will call the setter method.
Now here the point can be raised is we have shifted the dependency resolution logic some where else and that code is coupled with the instantiation of MessageService and if some implementation is changed then I will have to change that class but with spring also If I have to change implementation I have to make change in metadata that I have given before.
so here my question is what is different with DI? What is strongest point about DI here?
In short, the metadata change is desirable which enables configuration of a higher layer of abstraction rather than change in the application code. The configurable higher layer is then reusable and your lower layer of application code is easily testable. Dependency injection is one of the very old core design principles featuring in famous SOLID design principles. This design principle has featured into lots of frameworks out there - Spring being one of the most popular and evangelist of DI in Java world. There are already lots of good articles available to understand the necessity of DI- you can read them on Wikipedia and Microsoft library. And yes, then there are few gem of articles on Martin Fowler's site to understand it in depth here and here.
The point of dependency injection is reuse. Crafting your code correctly you can inject multiple implementations at runtime.
This is particularly useful for unit testing where you want to pass a mock object instead of a real one without modifying the object. By moving the dependency outside of the code and injecting it you can test your code without modifying it.
It also allows a separation of concerns. If the creation of the object is a complex affair you don't have to put that code in the class which uses it. Other code or classes can do the creation and just pass it into your class, which no longer has to worry about the specifics of how it was created. So moving it outside is an advantage. Think of complex objects created using frameworks. Good examples include instantiating a database driver or database session.
There are other specific instances where the reuse is practical but I would say these are the main ones I've seen for web applications and business code.
I'm new to using Spring with Neo4j and I have a question about #Autowire for a GraphRepository.
Most examples I've seen use one #Autowire per Controller, but I have two Nodes I need to modify at the same time when a particular method is called in the controller. Should I simply #Autowire the repositories for both nodes (eg per the code below)? Is there any impact if I do this in a second controller with the same repositories as well (so if I had a ChatSessionController which also #Autowired ChatMessageService and ChatSessionService)?
ChatMessageController.java
#Controller
public class ChatMessageController {
#Autowired
private ChatMessageService chatMessageService;
#Autowired
private ChatSessionService chatSessionService;
#RequestMapping(value = "/message/add/{chatSessionId}", method = RequestMethod.POST)
#ResponseBody
#Transactional
public void addMessage(#RequestBody ChatMessagePack chatMessagePack,
#PathVariable("chatSessionId") Long chatSessionId) {
ChatMessage chatMessage = new ChatMessage(chatMessagePack);
chatMessageService.save(chatMessage);
// TODO: Make some modifications to the ChatSession as well
}
}
Any help would be much appreciated! I've been googling and looking through Stackoverflow to understand this better but I haven't found anything yet. Any pointers in the right directions would be great.
Another underlying question is, should I be (and can I?) modifying other Nodes in a GraphRepository that handles a particular node? Eg Should my GraphRepository be able to modify my GraphRespository?
Thanks!
I'm not convinced that this is a SO question, it's not really a Neo4J or Spring question either, it is more about the architecture of your application. However assuming that you understand the negatives of class fan out, and how to use the #Transactional annotation to achieve what you want then the answer to your question is that it is just fine to have many Repositories (Neo4J or otherwise, autowired or otherwise) in your class and in as many classes as you want.
Neo4J transactions default to Isolation level READ_COMMITTED and if you need anything else, you need to add the guards/locks yourself. Nested transactions are consideredd tobe the same transaction. The Spring #Transactional annotation relies on proxies that you should be aware of as they have implications when calling methods from within the same class.
I would go through this tuotorial over at Spring Data and get your head around how real world vs domain vs node models differ, there will be cases where one repository impacts another node type but I would think it is often transparent to you (i.e adding relationships). You can do what you like in each repository (the generic nature of them is largely confined to all of the built in CRUD and queries derived from finder-method names (see documentation ) using the #Query annotation, and some queries have side effects, but largely you should avoid it.
As you start adding multiple repositories to multiple controllers I think that your code will begin to smell bad and that you should consider encapsulating this business logic off on its own somewhere, neatly unit tested. I also wouldn't tie myself to one controller per data object, it would be fine to have a single ChatController with a POST/chat/ to create a new session and POST /chat/{sessionId} to add a message. Intersting questions on Programmers:
How accurate is "Business logic should be in a service, not in a model?"
Best Practices for MVC Architecture
MVC Architecture — How many Controllers do I need?
I was thinking about some of my services.
Some of them looks like this:
#Service
public class UserService {
#Autowired
UserDao dao;
#Autowired
OtherService1 serv1;
#Autowired
OtherService2 serv2;
#Autowired
OtherService3 serv3;
....
}
I was thinking.. if this concept of autowiring other services into a single service is pretty common, why not creating a "Master-service" :
#Service
public class MasterService {
#Autowired
OtherService1 serv1;
#Autowired
OtherService2 serv2;
#Autowired
OtherService3 serv3;
...
#Autowired
LastService servN;
}
and autowiring this service in to all services.
#Service
public class AnyService {
#Autowired
MasterService masterSevice;
}
this way we wont have many services per service, but only a single one to rule them all..
Two questions rises:
1) Since masterService contain all services we have a loop in injection. can we solve it?
2) if the answer to question 1 is "yes" - is this "masterService" a good practice?
1) Spring is able to handle dependency loops in many cases, especially when not using constructor injections.
2) Despite this. You should absolutely avoid this design. It breaks many principles of good architecture:
Components should only have access to as few other components as needed. Demeter's Law
Separation of concerns. A service should not at the same time handle business logic, and presentation.
Abstraction levels. A service should not handle both a logical view of data, and a persistence view of it.
Breaking such principles may lead to bad situations such as:
Inability to follow code paths (a single request will go through 12 services in an order that is hard to understand and relies on many levels of conditional logic).
Difficulty to know which components rely on each-other.
Strongly coupled code (changing a low level service will lead to changes in high level services).
The advantages you gain from such a design are very small (you just avoid a few #Autowired annotations) and are not worth the risk.
Why would have a circular dependency? There is one service that contains all the other services, and no other service that contains it. Having said that, a circular dependency could be easily solved by setting the dependency as property and not as constructor arg.
I don't think so, it is nice pattern to declare kind of hierarchy (in endpoints for instance), but what are the pros of it in this way? You can Autowire every service that you want also without it.
1) MasterService doesn't necessarily contain a loop. If it does, then you'll run into problems, and it's much simpler not to construct your beans in a loop in the first place.
2) It's possible for this to be effective if you're injecting into lots of short-lived beans, but this approach has the downside that anyone who meddles with the MasterService instance can screw up the services for the other beans. You can hide this behind getter methods, but lumping everything together usually doesn't provide much benefit.
Instead, it's usually best to group related services together, maybe OtherService1 and OtherService2, and to place them on an interface. This makes mocking for testing much easier and keeps related concepts together (ideally in their own jars/modules).
I haven't come across such pattern before (one service containing other services).
What I commonly seen and used is something like below -
*SpecificController1 --> SpecificService1 --> SpecificDao1
SpecificController2 --> SpecificService2 --> SpecificDao2
Now, if SpecificService1 needs some functionality already available in SpecificService2, only then it will refer to SpecificService2.
So, I have few questions about the pattern described above:
How the MasterService would be used? i.e. any controller (or anyone) requiring any service would first use MasterService to get a reference to the actual service or MasterService would act as a delegate?
In what scenario, do you need such design and what are the advantages?
What is the difference using #Autowired annotation and new key ?
Let's within a class what would be the difference between :
#Autowired private UserDao userdao;
and
private UserDao userDao = new UserDaoImpl();
Is there an impact on the performance?
Besides low coupling, that others have already touched on, a major difference is that with the new approach, you get a new object every time, whether you want to or not. Even if UserDaoImpl is reusable, stateless and threadsafe (which DAO classes should strive to be) you will still create new instances of them at every place they are needed.
This may not be a huge issue at first, but consider as the object graph grows - the UserDaoImpl perhaps needs a Hibernate session, which needs a DataSource, which needs a JDBC connection - it quickly becomes a lot of objects that has to be created and initialized over and over again. When you rely on new in your code, you are also spreading out initialization logic over a whole bunch of places. Like in this example, you need to have code in your UserDaoImpl to open a JDBC connection with the proper parameters, but all other DAO classes have to do the same thing.
And here is where Inversion-of-Control (IoC) comes in. It aims to address just these things, by decoupling object creation and life-cycle from object binding and usage. The most basic application of IoC is a simple Factory class. A more sophisticated approach is Dependency Injection, such as Spring.
Is there an impact on the performance?
Yes, but it's most likely not going to be very significant. Using Springs dependency injection costs a little more in startup-time as the container has to be initialized and all managed objects set up. However, since you won't be creating new instances of your managed objects (assuming that is how you design them), you'll gain some runtime performance from less GC load and less object creation.
Your big gain however is going to be in maintainability and robustness of your application.
The above comments are correct, but here I am going add some example that helps to you.
Look We have 100 Classes that uses UserDao class, And you get dao instance like that:
private UserDao userDao = new UserDaoImpl(); in 100 places,
After few weeks the requirement changed and we need to use LdapUserDao or something similar
class LdapUserDao implements UserDao{
}
that implements UserDao. What do you do? How do you handle your new keywords, You tied impl class into usage.
If you use #Autowired in 100 places then from one place (if you use xml based config then, just go xml and switch to another UserDao from xml, if annotation the go to that component and switch Spring annotation to proper one) manage it, so in 100 places it appears. This is what is called DI pattern. This is whole purpose of DI
Another important thing is with spring annotation even you can manage object scope, but with new keyword no way(unles you do dumb singleton or something like that),
I am sure with new keyword you can no have
Prototype
Request
Single
Scoped objects
In terms of performance, It is quite difficult to say, unless to see your code. But I am sure at worst case they may have equal performance, otherwise springs way is fast, because As I know dao class should be singleton, not prototype, so whole project you will have on userdao object in spring way, with new way It depends where you are loosing reference to dao object. But Leave the performance. Do not consider performance over good design. All time 1st make it in good manner(not fast manner) with good design, then look it's performance.
You will get NullPointerException if you use
private UserDao userDao = new UserDaoImpl();
because it doesn't set the session reference that was declared in the *context.xml.
At runtime, you'll get a UserDaoImpl instance asigned in the userdao attribute in both cases.
But the first approach implies the ussage of the Dependency Injection pattern, that has some advantages over the second approach:
Your class now depends on an Interface, so it can work with any implementation of UserDao (maybe one that uses and RDBMS, other that uses XML files as a repository)
As you depend on an Interface now, Unit Testing and Mocking are pretty easy and straightforward.
Low-coupling is nice attribute to have in your code.
So you should prefer the second approach over the first, specially if your already using Spring (that's the idea behind an Inversion-Of-Control container)