#autowired vs new key? - spring

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)

Related

Spring autowiring based on service availability

I have a need of conditionally creating one of three possible implementations of a service depending upon the environment detected by a Spring application at runtime. If Service A is available, then I want to create a concrete implementation class that uses Service A as a dependency. If Service A is not available, then I want to create an implementation using Service B as a dependency. And so-on.
Classes which depend on the implementation will Autowire the Interface and not care what the underlying Service was that got selected for the particular environment.
My first stab at this was to implement multiple #Bean methods which either return a bean or null, depending on whether the Service is available, and to then have a separate #Configuration class which #Autowire(required=false) the two possible services, conditionally creating the implementation depending on which of the #Autowired fields was not-null.
The problem here is that when required=false, Spring doesn't appear to care whether it waits around for candidates to be constructed; that is to say, the class which tries to pick the implementation might be constructed before one or both of the required=false Beans gets constructed, thus ensuring that one or both might always be null, regardless of whether it may manage to initialize correctly.
It kind of feels like I'm going against the grain at this point, so I'm looking for advice on the "right" way to do this sort of thing, where a whole set of beans might get switched out based on the availability of some outside service or environment.
Profiles don't look like the right answer, because I won't know until after my Service beans try to initialize which implementation I want to choose; I certainly won't know it at the time I create the context.
#Order doesn't achieve the goal either. Nor does #Conditional and testing on the existence of the bean (because it still might not be constructed yet). Same problem with FactoryBean- it does no good to check for the existence of beans that might not have been constructed at the time the FactoryBean is asked to create an instance.
What I really need to do is create a Bean based on the availability of other beans, but only AFTER those beans have at least had a chance to try to initialize.
Spring Profiles is your friend. You can set the current profile by way of environmental variable, command-line argument, and other methods. You can annotate a Spring-managed component so that it's created for a certain profile.
Spring Profiles from the Spring Documentation
Well in this case it turned out to be a tangential mistake that influenced the whole wrong behavior.
To give some background, my first, naive (but workable) approach looked like this:
#Autowired(required=false)
#Qualifier(RedisConfig.HISTORY)
private RLocalCachedMap<String, History> redisHistoryMap;
#Autowired(required=false)
#Qualifier(HazelcastConfig.HISTORY)
private IMap<String, History> hazelcastHistoryMap;
// RequestHistory is an interface
#Bean
public RequestHistory requestHistory() {
if (redisHistoryMap != null) {
return new RedisClusteredHistory(redisHistoryMap);
} else if (hazelcastHistoryMap != null) {
return new HazelcastClusteredHistory(hazelcastHistoryMap);
} else {
return new LocalRequestHistory(); // dumb hashmap
}
}
In other #Configuration classes, if the beans that get #Autowired here aren't available (due to missing configuration, exceptions during initialization, etc), the #Bean methods that create them return null.
The observed behavior was that this #Bean method was getting called after the RLocalCachedMap<> #Bean method got called, but before Spring attempted to create the IMap<> by calling its #Bean method. I had incorrectly thought that this had something to do with required=false but in fact that had nothing to do with it.
What actually happened was I accidentally used the same constant for both #Bean names (and consequently #Qualifiers), so presumably Spring couldn't tell the difference when it was calculating its dependency graph for this #Configuration class... because the two #Autowired beans appeared to be the same thing (because they had the same name).
(There's a secondary reason for using #Qualifier in this case, which I won't go into here, but suffice it to say it's possible to have many maps of the same type.)
Once I qualified the names better, the code did exactly what I wanted it to, albeit in a way that's somewhat inelegant/ugly.
At some point I'll go back and see if it looks more elegant / less ugly and works just as well to use #Conditional and #Primary instead of the if/else foulness.
The lesson here is that if you explicitly name beans, make absolutely sure your names are unique across your application, even if you plan to swap things around like this.

Duplicated blocks of #Autowired beans

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.

Spring How its helpful [duplicate]

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.

Autowire two Neo4j GraphRepository in Spring

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?

Service layer in spring - autowire all services

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?

Resources