How to inject Spring Bean for factory method requiring MyClass.class parameter How to inject Spring Bean for factory method requiring MyClass.class parameter spring spring

How to inject Spring Bean for factory method requiring MyClass.class parameter


You can specify the constructor-arg element

<bean id="preferences" class="java.util.prefs.Preferences" factory-method="userNodeForPackage">    <constructor-arg type="java.lang.Class" value="com.path.MyController" /></bean>

This is explained in the official documentation here, section 5.4.1.

Arguments to the static factory method are supplied via elements, exactly the same as if a constructor had actually been used. The type of the class being returned by the factory method does not have to be of the same type as the class that contains the static factory method, although in this example it is. An instance (non-static) factory method would be used in an essentially identical fashion (aside from the use of the factory-bean attribute instead of the class attribute), so details will not be discussed here.


Well I don't know the xml based configuration way but I can tell you how you can instantiate it via Configuration class.

@Configurationpublic class Config {    @Bean(name="preferences")    public java.util.prefs.Preferences preferences() {        // init        return java.util.prefs.Preferences.userNodeForPackage(YourExpectedClass.class);    }}

P.S. :

You will need to add your configuration class/package for scanning either in web.xml if you are using complete annotation based approach [contextClass=org.springframework.web.context.support.AnnotationConfigWebApplicationContext] or in your config file as below :

<context:component-scan base-package="com.comp.prod.conf" />


 public class Preferences {       SomeBean someBean;     public void setSomeBean(SomeBean someBean){            this.someBean = someBean;     }       public static Preferences createSampleBeanWithIntValue(SomeBean someBean)     {         Preferences preferences= new Preferences();         preferences.setSomeBean(someBean);         return preferences;     }}  <bean id="someBean" class="java.util.prefs.SomeBean"/> <bean id="preferences" class="java.util.prefs.Preferences" factory-method="userNodeForPackage" >     <constructor-arg ref="someBean "/>        </bean>

Please see the reference

http://www.skorks.com/2008/10/are-you-using-the-full-power-of-spring-when-injecting-your-dependencies/