gpt4 book ai didi

java - 如何为需要 MyClass.class 参数的工厂方法注入(inject) Spring Bean

转载 作者:IT老高 更新时间:2023-10-28 13:52:37 25 4
gpt4 key购买 nike

我正在尝试将 java.util.prefs.Preferences bean 注入(inject)到我的主 Controller 中。 Controller 看起来像:

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

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

<bean id="preferences" class="java.util.prefs.Preferences" factory-method="userNodeForPackage" />

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

Preferences.userNodeForPackage(MyController.class);

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

环境信息:

Java 7
Spring 3.1

最佳答案

你可以指定 constructor-arg 元素

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

这在官方文档here中有解释,第 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.

关于java - 如何为需要 MyClass.class 参数的工厂方法注入(inject) Spring Bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18446230/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com