Is <context: annotation-config> necessary for annotation #Resource , #PostConstruct and #PreDestroy? - spring

I am new in spring and i want to know that if i write #Resource or #PostConstruct or #PreDestroy annotation on any method of any class then it is necessary to add "context: annotation-config" tag in xml file to register the method.
My confusion is that #Resource or #PostConstruct or #PreDestroy are JSR-250 annotation which are not specific to spring-framework then why "context: annotation-config" tag is added in config file(spring.xml).
I know that it is applicable for #Required and for #Autowired annotation.
Can anyone explain please ?

The thing is this that, no matter what the annotation is, actually it doesn't do anything, it just is kind of mark that tell the other thing that what it means. And when you add context: annotation-config in your xml file, when you start up the tomcat or other which will load the environment of Spring, then when it found context: annotation-config, it will register some beans that Spring has implemented which will scan your class to find annotation #Resource or #PostConstruct or #PreDestroy, and do the thing that it will actually do, such as instantiate Bean, bind the value and so on.

Related

How SpringBoot dependency injection works with different type of annotations

I recently started exploring Spring Boot. I see that there are 2 ways to define Beans in Spring Boot.
Define #Bean in the class annotated with #SprinBootApplication
Define #Bean in a class annotated with #Configuration
I am also confused about stereo-type annotation #Repository #Service #Controller etc.
Can someone please explain how dependency-injection works with these annotations?
Yes it is possible.
Either you use #Bean in any of your #Configuration or #SpringBootApplication class or mark the bean classes explicitly with annotations like #Service, #Component #Repository etc.
#Service or #Component
When you mark a class with #Service or #Compoenent and if spring's annotation scanning scope allows it to reach to the package, spring will register the instances of those classes as spring beans.
You can provide the packages to be included/excluded during scan with #ComponentScan
#Bean
#Beans are marked on factory methods which can create an instance of a particular class.
#Bean
public Account getAccount(){
return new DailyAccount();
}
Now in you application you can simply #Autowire Account and spring will internally call its factory method getAccount, which in turn returns an instance of DailyAccount.
There is a simple difference of using #Bean vs #Service or #Compoenent.
The first one makes your beans loosely coupled to each other.
In the #Bean, you have flexibility to change the account implementation without even changing any of the account classes.
Consider if your classes instantiation is a multi-step operation like read properties values etc then you can easily do it in your #Bean method.
#Bean also helps if you don't have source code access to the class you are trying to instantiate.
Spring Boot auto-configuration attempts to automatically configure your Spring application based on the jar dependencies that you have added.
You need to opt-in to auto-configuration by adding the #EnableAutoConfiguration or #SpringBootApplication annotations to one of your #Configuration classes.
You are free to use any of the standard Spring Framework techniques to define your beans and their injected dependencies. For simplicity, we often find that using #ComponentScan (to find your beans) and using #Autowired (to do constructor injection) works well.
One way is to define #Bean in the class annotated with
#SprinBootApplication
If you see #SprinBootApplication it is combination of many annotation, and one of them is #Configuration. So when you define #Bean in the Main class, it means it's inside #Configuration class.
According to Configuration docs :
Indicates that a class declares one or more #Bean methods and may be
processed by the Spring container to generate bean definitions and
service requests for those beans at runtime.
class annotated with #Configuration
When you define #Bean is a class annotated with #Configuration class, it means it is the part of spring configuration all the Beans define in it all available for Dependency-Injection.
I have also seen some code where neither of the 2 above approaches
have been used and yet dependency injection works fine. I have tried
to research a lot on this but could not find any concrete answer to
this. Is this possible?
I am assuming you are talking about Sterio-type annotation. Every sterio type annotation has #Component, according to docs :
Indicates that an annotated class is a "component". Such classes are
considered as candidates for auto-detection when using
annotation-based configuration and classpath scanning.

Spring injects dependencies in constructor without #Autowired annotation

I'm experimenting with examples from this official Spring tutorials and there is a dependency on this code:
https://github.com/spring-guides/gs-async-method/tree/master/complete
If you look at the code on AppRunner.java class, I have 2 questions:
When server is starting, if I put a breakpoint in this class's constructor, seems like in the constructor, the GitHubLookupService is provided by spring, using the #Service bean that was configured. BUT, there was no #Autowired annotation on the constructor, so how in the world this constructor get called with the right dependency? It was supposed to be null.
Is it an automatic assumption of Spring Boot?
Does Spring see "private field + constructor argument, and it assumes it should look for an appropriate bean?
Is it Spring Framework or Spring boot?
Am I missing something?
As I remember, it was mendatory to provide default constructor to beans / service etc. How come this class (AppRunner) doesn't have a default constructor?
How does Spring knows that it should run the constructor with the argument?
Is it because it is the only constructor?
Starting with Spring 4.3, if a class, which is configured as a Spring bean, has only one constructor, the #Autowired annotation can be omitted and Spring will use that constructor and inject all necessary dependencies.
Regarding the default constructor: You either need the default constructor, a constructor with the #Autowired annotation when you have multiple constructors, or only one constructor in your class with or without the #Autowired annotation.
Read the #Autowired chapter from the official Spring documentation for more information.
Think of it this way... Suppose you have the following component:
#Component
public class FooService {
public FooService(Bar bar) { /*whatever*/ }
}
When Spring is scanning this class, it wants to know how it should go about constructing an instance. It's using reflection so it can get a list of all of the constructors at runtime.
In this case, it is completely unambiguous how Spring must construct this instance. There's only one constructor so there is no decision to be made, and no ambiguity at all.
If you add #Autowired here, you are not narrowing anything down, and you are not giving Spring any extra information to help make its decision - its decision is already made because there is only one candidate.
And so, as a convenience, the Spring team decided #Autowired should be optional. Since its not helping the Spring framework to make a decision, its presence is just noise.
If your component has multiple constructors then you can use #Autowired on one of them to tell Spring "use this one, not that one".

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

Prevent autowiring by type for certain beans in Spring

In my spring context I am creating a service bean and a proxy for this service bean (explicitly). Both implement the same interface.
Can I ensure that autowiring cannot inject the target bean?
I would like to be able to use the target service with the #Resource or #Qualifier annotations, but when autowiring it should always be the proxy.
Any ideas?
Use the Primary annotation. It will indicate which bean should be use preferably when autowiring.
Hope this helps :)
You can put #Primary annotation in your proxy service like bellow:
#Primary
#Repository
public class ProxyOfSomeService implements SomeService
And after that when you use, #Autowired annotation on SomeService field, the ProxyOfSomeService will be injected by deafault.
But when you need the real service you can have it like bellow:
#Autowired
#Resource(name="someRealService")
private SomeService someService;
I think this serves your need, thanks!

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