如何为需要MyClass.class参数的工厂方法注入Spring Bean

我正在尝试将java.util.prefs.Preferences bean注入我的主控制器。 控制器看起来像:

@Controller class MyController { @Autowired private Preferences preferences; } 

application-context.xml文件为java.util.prefs.Preferences创建bean。 它使用工厂方法,所以我有以下条目来创建bean:

  

Preferences.userNodeForPackage(param)为参数提供与Preference相关的类。 在这种情况下,Spring需要通过执行调用来创建bean:

 Preferences.userNodeForPackage(MyController.class); 

如何将类传递给使用工厂方法实例化的spring bean? 谢谢

环境信息:

 Java 7 Spring 3.1 

您可以指定constructor-arg元素

    

这在第5.4.1节的官方文档中有解释。

静态工厂方法的参数是通过元素提供的,与实际使用的构造函数完全相同。 工厂方法返回的类的类型不必与包含静态工厂方法的类的类型相同,尽管在此示例中它是。 实例(非静态)工厂方法将以基本相同的方式使用(除了使用factory-bean属性而不是class属性),因此这里不再讨论细节。

好吧,我不知道基于xml的配置方式,但我可以告诉你如何通过Configuration类实例化它。

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

PS:

如果使用基于完整注释的方法[contextClass=org.springframework.web.context.support.AnnotationConfigWebApplicationContext]或在配置文件中,则需要在web.xml中添加用于扫描的配置类/包,如下所示:

  
  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; } }     

请参阅参考资料

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

首先使用xml文件或使用注释创建’Preferences’类的bean。
如果您使用xml配置创建bean以激活@Autowired注释function,则可以使用此
(要么 )


如果您使用注释创建bean。
注意:在spring servlet xml文件中定义上述标记

Spring框架提供了使用工厂方法注入bean的工具。 为此,我们可以使用bean元素的两个属性。

factory-method:表示将调用以注入bean的工厂方法。 factory-bean:表示将调用工厂方法的bean的引用。 如果工厂方法是非静态的,则使用它。 返回类实例的方法称为工厂方法。

 public class A { public static A getA(){//factory method return new A(); } } 

你能尝试将“偏好”作为“MyController”的属性。 就像是

    

然后在MyController中为首选项设置getter和setter方法。

我认为这应该有效。