spring: need for an example of using prototype bean in a web environment - spring

I wonder how can I properly inject a prototype bean to a singleton one in a web app. Consider this example:
<bean id="order" class="com.foo.Order" scope="prototype"/>
<bean id="orderService" class="com.foo.OrderService">
<property name="userPreferences" ref="userPreferences"/>
</bean>
I thought of using getBean() but isn't that a way to make my code dependent to spring itself?
I need a short java code example to demonstrate how to inject an order bean in my OrderService singleton.
Thanks

You can use jsr-330 Providers, just put:
#Autowired
Provider<Order> orderProvider;
in your singleton bean, and then use the provider:
public Whatever yourMethod() {
Order order = orderProvider.get();
}

Related

How to inject spring properties into wicket components?

I'm searching for a possibility to inject a property which is defined in a spring context (provided by a propertiesFactoryBean) into a wicket component. I know the way to inject beans into components by using the #SpringBean-Annotation, but whats the corresponding way for properties?
The way my property is defined:
<bean id="myPropertiesFactory" class="org.springframework.beans.factory.config.PropertiesFactoryBean">
<property name="properties">
<props>
<prop key="mySpringProperty">mySpringProperty</prop>
</property>
</bean>
Things I've tried. The way it works usually with self defined beans:
#Inject
#Value("${mySpringProperty}")
Using the name of the propertiesFactory to access the property value
#Inject
#Value("$myPropertiesFactory.properties.mySpringProperty")
Using the Value Annotation
#Value("#myPropertiesFactory['mySpringProperty']")
Using SpringBean
#SpringBean(name="myPropertiesFactory.mySpringProperty")
None of these solutions works. So to get mySpringProperty injected i use the workaround to create a bean of the type String which get's injected properly by wicket when i annotate the corresponding member of my component with SpringBean but i think there must be a better solution.
<bean id="mySpringPropertyBean" class="java.lang.String">
<constructor-arg type="java.lang.String" value="https://foobar.com" />
</bean>
Annotate
#SpringBean
private String mySpringPropertyBean;
#SpringBean only supports injection of spring beans. I suppose someone could implement a #SpringValue annotation that does what you want, but as far as I know noone ever did.
What I usually do is:
My wicket application class is a spring bean.
It has properties with #Value annotations - as the object is a spring bean, these are evaluated and set properly
I access the actual values by calling MyApplication.get().getXXX() or ((MyApplication)getApplication()).getXXX()
If the app grows and the number of attributes approach a limit, I refactor them into separate Settings or Config classes - each one a spring bean of it's own, accessible from the application class.
In your Wicket class use instead of #Value("${mySpringProperty}"):
#SpringBean
private PropertiesConfiguration propertiesConfiguration;
Create a new PropertiesConfiguration class:
#Component
public class PropertiesConfiguration {
#Value("${mySpringProperty}")
private String mySpringProperty;
//getters & setters
}
Use in your wicket class:
System.out.println("mySpringProperty=" + propertiesConfiguration.getMySpringProperty());

Spring inject bean is always singleton

We are using spring 3.2.
We defined a bean myAccountVO in spring.xml files and set the scope to prototype, but the spring creates this bean as singleton bean.
Here is the spring xml:
<bean name="myAccountVO1"
class="valueobject.AccountVO"
scope="prototype" >
<property name="accountNo" value="0105069413007" />
<property name="accountType" value="01" />
</bean>
The service class is:
#Service //I've tested the #Scope("prototype") but no luck
public class AccountSummary {
#Autowired //I also tested #Resource but same result
private AccountSummaryVO myAccountSummaryVO1;
AccountSummaryVO getAccount(){
return myAccountSummaryVO1
}
}
Later we use this service as:
#Autowired
AccountSummary accountSummary;
............
accountSummary.getAccount()
As far as I get the AccountSummary class, itself, is a singleton and will not be instantiated every time.
It seems are very basic usecase, but I don't know what am I missing.
I don't see where you are injecting myAccountVO1.
But I guess when you reveal the injected place that it's probably a member of a bean which itself is not in the scope prototype, e.g. #Service or #Controller. The service bean will be instantiated with a newly created myAccountVO1, but this instance stays there forever.
Change the scope of the containing bean. See 4.5.3 Singleton beans with prototype-bean dependencies.
This applies as well to the beans which have the service beans injected.

How to wire a SessionFactory into a Hibernate Interceptor with Spring? [duplicate]

I want to declare two beans and instantiate them using Spring dependency injection?
<bean id="sessionFactory" class="SessionFactoryImpl">
<property name="entityInterceptor" ref="entityInterceptor"/>
</bean>
<bean id="entityInterceptor" class="EntityInterceptorImpl">
<property name="sessionFactory" ref="sessionFactory"/>
</bean>
But Spring throws an exception saying "FactoryBean which is currently in creation returned null from getObject"
Why is inter-dependent bean wiring not working here? Should i specify defferred property binding anywhere?
Unfortunately the way container initialization works in Spring, a bean can only be injected in another bean once it is fully initialized. In your case you have a circular dependency that prevents either bean to be initialized because they depend on each other. To get around this you can implement BeanFactoryAware in one of the beans and obtain the reference to the other bean using beanFactory.getBean("beanName").
neesh is right, Spring doesn't do this out of the box.
Interdependent beans hint at a design problem. The "clean" way to do this is to redesign your services in such a way that there are no such odd dependencies, of course provided that you have control over the implementations.
You can implement a BeanPostProcessor that sets the dependency.
Or...
See Costin's reply here:
http://forum.springframework.org/showthread.php?t=19569&highlight=circular+dependencies
See Andreas' reply here:
http://forum.springframework.org/showthread.php?t=29572&highlight=circular+dependencies
you can extend the ApplicactionContext that are using and override the method createBeanFactory()
protected DefaultListableBeanFactory createBeanFactory(){
DefaultListableBeanFactory beanFactory = super.createBeanFactory();
// By default this is false;
beanFactory.setAllowRawInjectionDespiteWrapping( true );
return beanFactory;
}
This works, but be careful because this allows circular references.

Replace spring bean in one context with mock version from another context

I'm writing an integration test where an application context xml is initialized during startup. There are several test methods in the test class which make use of a specific bean 'X'(already defined in the xml). My actual requirement is to mock bean X only for one of the test methods.
Inside a test method: I tried creating a separate application context using ClassPathXMLApplicationContext with only the mock bean 'M'.
Now I have two Application Contexts (AC):
1. One created during test case startup (which contains the actual bean X) and
2. One created using ClassPathXMLApplicationContext within the test method (which has the mock bean M).
I want to replaced the actual bean definition 'X' within AC:1, using the mock bean definition 'M' from AC:2.
Can somebody throw some light on this please?
You can :
use the Profile annotation if you have spring 3.1.
use the Primary annotation
use qualifiers
wire the bean yourself in the spring context
and i'm sure there are even more options.
There is not a clear way to replace a a bean in a refreshed ApplicationContext unless you close it and refresh it again.
To emulate it, the common approach is to use a Proxy of the bean that you want to replace and change the target at runtime.
You can do it easily using the framework aop support classes:
<bean id="realBean" class="RealClass" />
<bean id="mockBean" class="MockClass" />
<bean id="targetSource" class="org.springframework.aop.target.HotSwappableTargetSource">
<constructor-arg ref="realBean" />
</bean>
<bean id="bean" class="org.springframework.aop.framework.ProxyFactoryBean">
<property name="targetSource" ref="targetSource" />
</bean>
#Test
public void testWithMockBean() {
Object real = targetSource.swap(mock);
....
// do your test work
...
targetSource.swap(real);
}
Create a testApplicationContext with
<beans>
<import resource="classpath*:appContext.xml" />
<bean id="mockbeanOfX" class=....../>
</beans>
and then load this test application context in your testcase. Now you can get the mock bean from the application context and pass it whereever needed.

Spring injection bind toInstance

Is there a way to bind an injected object to a specific instance using Spring DI similar to Google Guice's
bind(MyClass.class).toInstance(myclassobject);
If the constructor or member variable is annotated with #Autowired, Spring will try to find a bean that matches the type of the Object. You can get similar functionality to the annotation using #Qualifier, for example:
bind(MyClass.class).annotatedWith(Names.named("main")).toInstance(myclassobject);
would become in Spring:
#Autowired #Qualifier("main") private MyClass myClassObject;
<bean name="myClassObject" class="example.MyClassImpl">
<qualifier value="main"/>
</bean>
See http://static.springsource.org/spring/docs/2.5.x/reference/beans.html#beans-autowired-annotation for more.

Resources