What is the most appropriate way of injecting daos in services, services in controllers in Spring? - spring

There are many annotations in the Spring framework like #Component, #Service, #Repository, #Service #Resource and #Autowired etc.
What is the most appropriate way of injecting my daos in services, and my service class in the Spring Controller.
With so many annotations it is getting confusing especially with #Autowired working for all situations.

#Service and #Repository are just "sub-annotations" for #Component to specify the bean a bit more (to separete Services from Repositories for more sophisticated stuff). From the point of injection this three are equal.
For injection, there are 3:
#Resource
#Inject
#Autowired
#Autowired is the most powerful annotation, but #Resource (JSR-250) and #Inject (JSR-330) are standardized. — Anyway if you not plan to reuse your application in a non-Spring environment, then I would not pay to many attention to this concern.

See Annotation based configuration in Spring, best Spring Annotation tutorial for me.

I prefer to avoid annotations, especially if they start getting confusing. Nothing wrong with good old getter and setters in this case. Just gotta wire the bean on your own, which isn't so difficult that annotations are necessary.

Related

What exactly happens in spring boot when I use #Service?

I know that we used #Service for the business logic, but what exactly Spring do when he sees this annotation? Can someone please exaplain it, if possible with the example. F.ex when we write #Autoweired, it allows Spring to resolve and inject collaborating beans into our bean. Thanks In advance
There is no difference at all as far as I know.
You can use #Component annotation as well on your service class and it will work fine. Spring will recognize and scan that for bean creation.
#Service annotation contains #Component in it, similar to the fact that #RestController has #Controller as part of it, but in controller theory, #RestController does bring some additional features ( #Controller + #ResponseBody = #RestController ).
Overall it's just good practice to annotate service classes with #Service, and persistence classes with #Repository ( #Repository does have additional features over #Component like transaction rollback ), but all these stereotype annotations contain #Component annotation for Spring to be able to scan them and register in Spring container for bean creation.
In my opinion, #Service is just used to make your code more readable and structured, but makes no difference if you would use #Component for your Service layer.

Spring #Transactional and #Service

I'm working in a company where JPA #transactional are used within #Component beans. I've always been told that #Transactional should be used inside #Service beans. Does someone could explain spring mechanisms differences between those and what are the best pratctices .. and why
There is no difference.
Also, #Service and #Component are the same. #Service is just a stereotype that developers often use to indicate that the Spring Bean is kind of a Service (maybe in a DDD meaning or not)
First of all, there is no difference.
From the spring javadoc
#Component
Indicates that an annotated class is a "component". Such classes are considered candidates for auto-detection when using annotation-based configuration and classpath scanning.
...
#Transactional
Indicates that an annotated class is a "Service", originally defined by Domain-Driven Design (Evans, 2003) as "an operation offered as an interface that stands alone in the model, with no encapsulated state."
May also indicate that a class is a "Business Service Facade" (in the Core J2EE patterns sense), or something similar. This annotation is a general-purpose stereotype and individual teams may narrow their semantics and use it as appropriate.
This annotation serves as a specialization of #Component, allowing for implementation classes to be autodetected through classpath scanning.
Frankly speaking, they behave in the same way.
By using #Transactional annotation on a public method or class it simply creates a proxy with transaction code for you.
IMO great explanation of #Transactional
Spring Stereotype Annotations

When to use Spring #Autowire annotation

Recently I had discussion with my friend regarding usage of Spring #Autowire annotation on entity(JPA) classes.
In our project we are using #Autowire annotaion to inject Entity but my friend suggesting not to use #Autowire annotaions on entity classes. When I asked why? He dont have the proper answer for that. So i just wanted to know are there any disadvantages using #Autowire annotaion on entity classes.
Also please explain when to go for #Autowire annotaion or not with example.
Thank in advance.
#Entity and #Autowire are not interchangeable.
#Entity annotation indicates that the JavaBean is a persistent entity.This is actually a JPA annotation and not a Spring Annotation.
#Entity will be used in the sessionFactory by the packagesToScan poroerty.
#Autowired: inject a resource by-type, i.e. by the class or by the interface of the annotated field or contractor. See my answer Inject and Resource and Autowired annotations
#Autowired is used to inject dependencies as an alternative to setting it via xml configurations
Maybe this answer will help you understand
Hibernate - spring annotated entities not scanned from within jar
UPDATE:
Following the comment bellow:
Company is your domain object, so you don't need to use spring in this case.
<bean id="company" class="xxx.Company"/>
The above will return the same instance with #autowire.
Even if you switch to scope="prototype" I don't see any reason to use spring for that.
You should have a service that will be used to CRUD company e.g.
CompanyService, this service will be a single tone so you will use #Autowire to inject it to the controller and it will use your JPA framework to implement CRUD's
To create a new company you will use:
Company c = new Company //this probably will be binded from your ui form
companyServic.saveOrUpdate(c);
See the following answer spring rest service - hibernate dao - annotations - pojo - namedqueries.
For common practice of DAO and services.
#Autowire is an annotation used to perform a dependency injection, its almost similar to the standard #Inject you can take a look at the spring reference manual to see the difference between those two annotations.
#Entity is a part of the jpa framework its used to mark a class as persistent, spring does not implement an equivalent annotation.

Use Spring annotation to inject dependency

In my project, i see a spring dependency inujection syntax like this in my integration layer:
applicationContext.getBean("beanName");
where applicationContext instance of ClasspathXMLApplicationContext and "beanName" is defined in the spring xml.
If I want to inject it with Annotation, which one should I use? #Inject,#Autowired,#Resource. Seems like I cna use any one of these and I cannot seem to be able to decide which one.
This is SPring integration layer , not MVC layer but i dont think that makes any difference.
#Inject and #Autowired do the same thing, it autowires by type. #Inject is preferred because it is a java annotation and does not couple you to Spring
#Resource autowires by name. This is useful when you have many beans of the same type. You can also use #Named along with #Inject for the same behavior.
#Inject is synonymous to #Autowired.
#Autowired moreover offers optional injection #Autowired(reqired=false) #Inject doesn't have this option.
#Inject and #Resource is standardized in JSR-299 so it should be preffered if possible.
in short, order in which mentioned annotations match dependency to be injected:
#Autowired and #Inject
Matches by Type
Restricts by Qualifiers (#Qualifier annotation)
Matches by Name
#Resource
Matches by Name
Matches by Type
Restricts by Qualifiers (#Qualifier, ignored if match is found by name)
You can find more about these annotations here:
http://blogs.sourceallies.com/2011/08/spring-injection-with-resource-and-autowired/
#Inject and #Autowired are similar. The native Spring annotation is #Autowired, even Spring also support the Java #Inject annotation, that makes the same.
#Resource is Java annotation, Spring also support that annotation. It means JNDI resource.
See
http://static.springsource.org/spring/docs/3.2.x/spring-framework-reference/html/beans.html#beans-annotation-config
http://docs.oracle.com/javase/7/docs/api/javax/annotation/Resource.html
http://docs.oracle.com/javaee/6/api/javax/inject/Inject.html

What is the difference between #Inject and #Autowired

i am just wondering what is the difference between #Inject & #Autowired
when to use each one ?, or they are doing the same thing ?
and if i have a spring bean which have a scope:
#Service
#Scope("singleton")
can i make dependency injection for it with both with no problems ?
thanks in advance.
From what I know, they do the same. #Inject is an annotation from javax.inject, which is only the API for dependency injection. In Spring you can use both, as I think Spring provides an implementation for #Inject which does the same thing as #Autowired in Spring environments.
Matthias Wessendorf blogged about this here: http://matthiaswessendorf.wordpress.com/2010/04/20/spring-3-0-and-jsr-330-part-2/
How about reading the documentation?
JSR 330's #Inject annotation can be used in place of Spring's
#Autowired in the examples below. #Inject does not have a required
property unlike Spring's #Autowired annotation which has a required
property to indicate if the value being injected is optional. This
behavior is enabled automatically if you have the JSR 330 JAR on the
classpath.
I think it is worth pointing out that, if you use #Autowired, you are creating a dependency on Spring, where using #Inject, you will be able to swap out another dependency injection framework that supports JSR 330.
First, #Autowired is defined by Spring Framework but #Inject came from "Dependency Injection for Java" (JSR-330)"
Second, #Inject doesn't take required attribute so if it fails to find any bean, it will fail with an error but #Autowired can come with required=false and will allow a nullable field.
Third, Advantage of #Inject annotation is that rather than inject a reference directly, you could ask #Inject to inject a Provider. The Provider interface enables, among other things, lazy injection of bean references and injection of multiple instances of a bean.

Resources