Cyclic dependencies in Spring - spring

IF I have bean A which refer to bean B and bean B depends upon bean A. In this scenario spring throws ObjectCurrentlyInCreationException ,but how internally it happen and on which object it will throw this error.
For Eg:
<bean id='A'>
<ref bean='B'>
</bean>
<bean id='B'>
<ref bean='A'>
</bean>

If your classes A and B have default constructors (A(), B()), I believe everything should go well. Possible dupe of this question: Circular dependency in spring

This is typical example of Circular dependency in Spring. Spring can resolve circular dependencies through setter - injection. Objects are constructed before the setter methods are invoked. The default constructors are needed for both ( rather all the classes involved in circular dependency) classes in order to help Spring construct the empty objects before calling the setter methods

Related

Spring bean scope : singleton and Prototype

Case 1 : Suppose we are injecting singleton bean inside prototype bean then how many instances will be created if we call prototype bean.
Consider the scenario :-
<bean id="a" class="A" scope="prototype">
<property name="b" ref="b">
</bean>
<bean id="b" class="B">
Case 2: Suppose we are injecting Prototype bean inside singleton bean then how many instances will be created if we call singleton bean.
Consider the scenario :-
<bean id="a" class="A" >
<property name="b" ref="b">
</bean>
<bean id="b" class="B" scope="prototype">
I am answering a part of your question.
Case2: Singleton beans with prototype-bean dependencies
With this configuration, it is expected that when ever you fetch A from application context, it will be wired with a new B as we declared the B bean is of prototype scope. But this will not happen.
When the application context gets initialized, it sees that A is a singleton bean and initializes it to the context after wiring it with all the dependencies set. So from then onwards when we request context for A, it return the same bean every time, So you will also get the same B everytime.
You can solve/overcome this by using Lookup method injection. Refer this article.
The singleton bean will always refer to the same object. The prototype will have as many instances created as many times that bean is referenced. The use cases you provided don't change this paradigm.

How many instances created for singleton bean referring to a session bean/prototype bean

I have a doubt about the number of instances that will be created in the scenario mentioned below, when Spring Framework is used:
The bean configuration is like this
<bean id="a" class="A">
<property name="b" ref="b"/>
</bean>
<bean id="b" class="B" scope="session"/> or
<bean id="b" class="B" scope="prototype"/>
By default, bean "a" has singleton scope. So there is a singleton bean with a reference to a bean with session scope or prototype scope.
In this case, if there are 2 simultaneous requests to the application, then how many instances of A will be created and how many instances of B will be created?
It will be of great help if anyone can explain how this works.
Thanks,
Divya
The singleton scope
When a bean is a singleton, only one shared instance of the bean will be managed, and all requests for beans with an id or ids matching that bean definition will result in that one specific bean instance being returned by the Spring container.
To put it another way, when you define a bean definition and it is scoped as a singleton, then the Spring IoC container will create exactly one instance of the object defined by that bean definition. This single instance will be stored in a cache of such singleton beans, and all subsequent requests and references for that named bean will result in the cached object being returned.
The session scope
With the above bean definition in place, the Spring container will create a brand new instance of the bean , for the lifetime of a single HTTP Session.
According to Spring framework reference, a different approach needs to be followed in cases where a class which "lives longer"(singleton bean in this case) needs to be injected with another class having a comparatively shorter life-span(session-scoped bean). The approach is different for prototype & singleton scope though.
In your XML, what we want is that the singletonBean instance should be instantiated only once, and it should be injected with sessionBean. But since sessionBean is session-scoped(which means it should be re-instantiated for every session), the configuration is ambiguous(as the dependencies are set at instantiation time and the session scoped value can change later also).
So instead of injecting with that class, its injected with a proxy that exposes the exact same public interface as sessionBean. The container injects this proxy object into the singletonBean bean, which is unaware that this sessionBean reference is a proxy. Its specified by writing this tag in the sessionBean:
<aop:scoped-proxy/>
XML Configuration:
<bean name="singletonBean" class="somepkg.SingletonBean">
<property name="someProperty" ref="sessionBean"/>
</bean>
<bean name="sessionBean" class="somepkg.SessionBean" scope="session">
<aop:scoped-proxy/>
</bean>
When a singletonBean instance invokes a method on the dependency-injected sessionBean object, it actually is invoking a method on the proxy. The proxy then fetches the real sessionBean object from (in this case) the HTTP Session, and delegates the method invocation onto the retrieved real sessionBean object.
Alse please refer this for more info.
Singleton beans with prototype-bean dependencies
Lookup Method Injection
When you use singleton-scoped beans with dependencies on prototype beans, be aware that dependencies are resolved at instantiation time. Thus if you dependency-inject a prototype-scoped bean into a singleton-scoped bean, a new prototype bean is instantiated and then dependency-injected into the singleton bean. The prototype instance is the sole instance that is ever supplied to the singleton-scoped bean.
However, suppose you want the singleton-scoped bean to acquire a new instance of the prototype-scoped bean repeatedly at runtime. You cannot dependency-inject a prototype-scoped bean into your singleton bean, because that injection occurs only once, when the Spring container is instantiating the singleton bean and resolving and injecting its dependencies.
<!-- a stateful bean deployed as a prototype (non-singleton) -->
<bean id="command" class="fiona.apple.AsyncCommand" scope="prototype">
<!-- inject dependencies here as required -->
</bean>
<!-- commandProcessor uses statefulCommandHelper -->
<bean id="commandManager" class="fiona.apple.CommandManager">
<lookup-method name="createCommand" bean="command"/>
</bean>
Lookup method injection is the ability of the container to override methods on container managed beans, to return the lookup result for another named bean in the container. The lookup typically involves a prototype bean as in the scenario described in the preceding section. The Spring Framework implements this method injection by using bytecode generation from the CGLIB library to generate dynamically a subclass that overrides the method.
Refer lookup method injection.
Follow for more detailed example and information.
If we use the way as mentioned in question spring IOC will create always return the same object as singleton, In order to inject prototype bean inside singleton we have two way
1) Lookup method injection
2) Scoped Proxies
see more detail here
First of all, I don't think it is valid to define a bean, both with session and prototype scopes at the same time with the same bean id.
How many instances created for singleton bean referring to a prototype bean?
In your case: one
In general: depending on how you access the bean:
One
#Component
class MySingletonBean{
#Autowired
MyPrototypeBean b;
}
Two
#Component
class MySingletonBean{
#Autowired
MyPrototypeBean b;
#Autowired
MyPrototypeBean bSecondInstance;
}
Or more
#Component
class MySingletonBean{
#Autowired
javax.inject.Provider<MyPrototypeBean> providerOfB;
void accessMultipleInstances(){
MyPrototypeBean bInstance1 = providerOfB.get();
MyPrototypeBean bInstance2 = providerOfB.get();
MyPrototypeBean bInstance3 = providerOfB.get();
//.....
}
}
Note: MyPrototypeBean is considered to have been marked with: #Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE). If you omit it ,then in all the above cases you will reference the same singleton instance.
Regarding session-scoped bean:
One per session.
According to this answer spring will automatically create a proxy which targets different instance depending on the session.
This means that in all the above cases you will get access to the same instance while you are on the same session.
Regarding the provided xml config:
To me it would be more meaningful something like this:
<bean id="a" class="A">
<property name="b" ref="b"/>
<property name="b2" ref="b2"/>
</bean>
<bean id="b" class="B" scope="session"/> or
<bean id="b2" class="B" scope="prototype"/>
In which case you would get one instance per session for b and one and only instance for b2 because you use it from a singleton and you don't use the provider or some similar pattern.

Spring bean creation

Is it possible to create to bean with same id with same class with different property in spring ? Like:
<bean id ="a" class= "com.tofek.A"
<property message = "khan"/>
</bean>
<bean id = "a" class = "com.tofek.A"
<property message="tofek"/>
</bean>
As per my understanding it will create, but while fetching the bean using getBean() method it will give exception like NoBeanDefinitionFoundException.
Please correct my understanding if I'm wrong?
Make sure your spring context is loaded sucessfully.
Answering your question. You can have two identical bean definitions in two different sprintContext configurations.
The bean from second context will override bean created by first one.
For example :
context1.xml
<bean id="bean1" class="org.springframework.beans.TestBean"/>
context2.xml
<bean id="bean1" class="org.springframework.beans.TestBean"/>
then, the bean from context2.xml will override bean created by contex1.xml.
It of course depends on order of creating spring contexts. The laters overrides the ones made before.
You can use getBean() to fetch bean by type or name. In this case, both bean have same id's and types, the spring wouldn't know which one you want to fetch.

Spring AOP - Error Generating proxies

I'm using spring AOP's around advice to capture processing time of a transaction. I'm getting the following error during application startup
error creating bean "coreMessageResourceAccesor"
Could not generate CGLIB subclass of class
[class org.springframework.context.support.MessageSourceAccessor]:
Common causes of this problem include using a final class or a non-visible class;
nested exception is java.lang.IllegalArgumentException:
Superclass has no null constructors but no arguments were given
I identified what the problem is with the help of this thread. But I cannot change coreMessageResourceAccesor bean to use setter based injection because its using a spring class & that class doesn't have no arg constructor
Below is the configuration for the bean
<bean id="coreMessageSourceAccessor"
class="org.springframework.context.support.MessageSourceAccessor" >
<constructor-arg type="org.springframework.context.MessageSource"
ref="coreMessageSource" />
</bean>
I would really appreciate if someone could help. Thanks for your time.
You don't need really need to configure MessageSourceAccessor accessor as a bean, it's generally easier to instantiate it manually as required. So rather than inject the MessageSourceAccessor into your beans, inject the raw MessageSource, and then wrap it in a MessageSourceAccessor as required (i.e. using new MessageSourceAccessor(messageSource)).
You can then put the advice around the MessageSource rather than the MessageSourceAccessor, which will work better. Also, MessageSourceAccessor will not itself add any significant processing time, it's just a thin wrapper around MessageSource.

when spring bean is loaded and if i have a constructor and setters which one will be called first?

This is a basic question - when spring bean is loaded and if i have a constructor and setters which one will be called first?
Thanks
The constructor must be called before any setter methods are called. Use the init-method to tell Spring to invoke some logic after the setters are called:
<bean class="my.CoolClass" init-method="startup">
<constructor-arg value="Foo" />
<property name="bar" value="baz" />
</bean>
Doesn't the constructor have to be called first? The setters are instance methods so that can't called until the object is instantiated.
I don't think Spring provides any guarantees about the order in which setters are called. It would be good practice to make your beans work regardless of which order the setters are called. If you want to do some processing after all the setters have been called, you might find that it's convenient to use a post construction method. Or if you are using XML configuration rather than annotations, an initialization method might suit.
I wrote simple XML config and step through Spring source code in debugger.
Seems that with Spring 3.x it's possible to combine constructor-arg and property in XML bean definition (check doCreateBean in AbstractAutowireCapableBeanFactory.java, which call createBeanInstance - constructor and populateBean next - setters).
See also https://softwareengineering.stackexchange.com/questions/149378/both-constructor-and-setter-injection-together-in-spring/

Resources