Does the test class create implementations to inject in spring dependency injection - spring

In this example on spring dependency injection here
Whne the final test class is run, after this line:
MySpringBeanWithDependency test = (MySpringBeanWithDependency) factory
.getBean("mySpringBeanWithDependency");
Which implementation of writer class will get injected? The test class still is responsbile for creating an actual implementation and injecting it before calling business methods on the Writer. Is it true?

In both the annotation-based example and the XML-based example, Spring will inject the NiceWriter bean into the MySpringBeanWithDependency bean.
For the annotation example, this is because the NiceWriter class is annotated with #Service (while the Writer class is not) and Spring will discover this via classpath scanning and autowire it into MySpringBeanWithDependency.
For the XML example, this is because the NiceWriter class is used to define the bean with id writer, which is referenced as the "writer" property of the bean with id mySpringBeanWithDependency.
In both cases, the MySpringBeanWithDependency bean is instantiated with dependencies injected via Spring, and is thus ready to use. It is not responsible for managing its IWriter dependency. This is why dependency injection (DI for short) usually goes hand-in-hand with inversion-of-control (IoC for short). Spring provides an IoC container that uses DI.

Related

IS Spring Context and Spring IOC container both are same and ApplicationContext is part of it?

I know what is application Context. It is an interface which provides spring beans.
All beans get initialized in Spring IOC containers.
But How all three are connected. Could you please explain.
Spring beans are the instances of classes that spring manages. You create classes and "mark" them to be spring managed (putting #Component, using #Bean in java configuration and so forth - there are many ways to tell spring that the instance of some particular class should be managed by spring)
When spring starts it creates an application context with is a registry of all beans it resolves.
Spring can inject one bean into another and its the way of spring to instantiate beans.
The principle of "providing dependencies by external container" as opposed to maintaining dependencies by class itself called Inversion of control, and spring implements this concept.
Update 1
There is no such a thing as "spring context" technically speaking
Spring IOC container is a framework that manages the beans (your classes) by means of providing a technical abstraction called application context (its a real interface in java with implementation inside the spring code).
In order to benefit from spring your Beans should have dependencies between them. In this case spring framework that implements IOC principle can "inject" (provide, resolve) dependencies between beans.
Here is an example:
#Component
class A {
}
#Component
class B {
#Autowired
private A a;
}
When spring container instantiates class B (creates the object : new B()) it "understands" that this instance (we call it bean because it's managed by spring) has a "dependency" on class A and since A is also managed by spring, it can "inject" (read put a value) into the property a of class B.
This is called an Inversion of Control. You, as a programmer do not have to instantiate property b by yourself, spring does it for you.

Spring Implementation of Common Annotations

How Spring able to read or implement the Annotations called #Autowired, #Component and where the logic available in spring source code?
Spring context understand annotation by set of classes which implements bean post processor interface. so to handle different type of annotation we need to add different annotation bean post processors.
if you add in you configuration xml then you need not to add any annotation bean post processors.
Post processor provide methods to do pre and post processing for each bean initialization. you can write your own bean post processors to do custom processing by created a bean which implements BeanPostProcessor interface.
Annotations are metadata that can be read from the java source code. Spring Container understands what has to be done when it encounters these annotations in a source file.
Read through on each of these annotations.
Component
Autowire
More on Autowiring
1.4.5. Autowiring Collaborators
The following class does the autowiring magic.
AutowiredAnnotationBeanPostProcessor

Spring Boot Scanning Classes from jars issue

In my sample spring boot application, i have added a dependency of a custom jar. My sample application has a support for web and jpa.
The jar which i've created contains a Spring MVC controller. Below is the sample code
#Controller
public class StartStopDefaultMessageListenerContainerController {
#Autowired(required=false)
private Map<String, DefaultMessageListenerContainer> messageListeners;
I haven't manually created a bean instance of this controller anywhere in my code.
Problem - When i start my spring boot application by running the main class, i get an error in console that prob while autowiring DefaultMessageListenerContainer.
My question here is, even though this class StartStopDefaultMessageListenerContainerController is just present in the classpath, it's bean shouldn't be created and autowiring should not happen. But spring boot is scanning the class automatically and then it tries to autowire the fields.
Is this the normal behavior of spring and is there anyway i can avoid this?
If the StartStopDefaultMessageListenerContainerController class is part of component scanning by spring container, Yes spring tries to instantiate and resolve all dependencies.
Here your problem is #Autowired on collection. Spring docs says,
Beans that are themselves defined as a collection or map type cannot be injected through #Autowired, because type matching is not properly applicable to them. Use #Resource for such beans, referring to the specific collection or map bean by unique name.
And also Refer inject-empty-map-via-spring

Why proxy is not used to autowire

I can not find any reason why every autowired bean are not autowired by proxy. I know that becasue #Transactional annotations do not work and I checked autowired component during debugging in eclipse. Of course every component implements some interface and I use #Autowired annotations in relation to the interface.
I have only one configuration of aop:
<tx:annotation-driven transaction-manager="transactionManager" />
I use JPA with hibernate, spring-mvc,spring-webflow, spring-security and spring-data. Interfaces which extends org.springframework.data.repository.CrudRepository are autowired by proxy. But my components are not. For example I have class MyClass which implement MyInterface:
#Service
public class MyClass implements MyInterface {
#Autowired
MyCrudReposiotry reposiotry;
....
}
If I autowire MyInterface somewhere:
#Autowired
MyInterface mi;
then mi is just reference to MyClass object, repository is refrence to proxy org.springframework.aop.framework.JdkDynamicAopProxy. Very interesting is that in testing mi is reference to proxy. My test's context does not contain web-flow and mvc configuration.
Maybe there is some indirect aop configuration which I should check. What can switch the autowiring by proxy off?
My guess is that you are scanning for the same components twice. You probably have a in your root context (for the ContextLoaderListener) and one for the DispatcherServlet. NO if the both scan for the same classes you end up with duplicated (and one proxied and one non proxied instance).
Proxying and auto wiring are independent of each other. When you use #AutoWired it finds another bean that implements the required interface and injects it. The bean instance it finds might be a normal object or a proxy - it doesn't matter to Autowired.
Proxies are created for certain beans automatically by spring. As you have noticed one scenario in which this happens is when you use #Transactional. When the spring container instantiates a bean which has the #Transactional annotation the object gets wrapped in a proxy. The actual object is replaced by the proxy in the context. This is done so that spring can intercept calls to those methods and add the begin / commit transaction calls before and after the method call. This is implemented by the spring-aop module. Any feature that relies on AOP (#Transactional, #Secured) will result in creation of a proxy.
The other case where proxies are used is to create an implementation on the fly. In case of the CRUDRepository you are required to only implement the interface. The implementation of that is created on the fly using the same proxy infrastructure.

Spring setter dependency injection after all beans have been created

I have a set of Spring beans created using constructor injection. Since there are (by design) circular references to other beans, I'd like to post-process the beans once they are all created to inject the references to other beans.
Initial attempts at using BeanPostProcessor show that the BeanPostProcessor is running after EACH bean is instantiated, not waiting until all have been instantiated.
Does Spring provide a mechanism for post-processing as set of beans after all have been created?
If you're creating the beans in an ApplicationContext, the ApplicationContext fires ApplicationEvents to any registered ApplicationListener callbacks. One of those should tell you when all the beans in the context are wired together via Spring.
Here's what the documentation says about circular dependencies:
If you use predominantly constructor injection, it is possible to
create an unresolvable circular dependency scenario.
For example: Class A requires an instance of class B through
constructor injection, and class B requires an instance of class A
through constructor injection. If you configure beans for classes A
and B to be injected into each other, the Spring IoC container detects
this circular reference at runtime, and throws a
BeanCurrentlyInCreationException.
One possible solution is to edit the source code of some classes to be
configured by setters rather than constructors. Alternatively, avoid
constructor injection and use setter injection only. In other words,
although it is not recommended, you can configure circular
dependencies with setter injection.
Unlike the typical case (with no circular dependencies), a circular
dependency between bean A and bean B forces one of the beans to be
injected into the other prior to being fully initialized itself (a
classic chicken/egg scenario).
I would just use setter injection in this case, or try to avoid the circular dependency in the first place. Another solution is to make one of the beans BeanFactoryAware, and to lookup the other bean from the bean factory when the reference is needed.

Resources