简体   繁体   English

从静态工厂方法创建工厂,然后在该ID上调用静态工厂方法

[英]Create factory from static factory method, then call static factory method on that id

I can create an object from a static factory object like so: 我可以从静态工厂对象创建对象,如下所示:

<bean id="myFactory" class="com.myco.MyFactory1" factory-method="createFactory">
  <constructor-arg value="aString" />
</bean>

Now I want to use the id 'myFactory' to call its static 'createFactory' method. 现在,我想使用id“ myFactory”调用其 静态 “ createFactory”方法。

In java something like: 在Java中类似:

ObjectFactory objectFactory = MyFactory.createFactory().createFactory(); //Last createFactory method returns type ObjectFactory

That is invalid Java code. 那是无效的Java代码。 It assumes your MyFactory has two methods with the same name - one static and one non-static. 假设您的MyFactory有两个同名的方法-一种是static ,另一种是非静态的。 And this is not possible. 这是不可能的。

In case you are invoking the same static method twice, or invoking a method on another object - well, you can easily invoke it only once / merge the two invocations, into a, say createObjectFactory() 如果您要两次调用同一个静态方法,或者在另一个对象上调用一个方法,那么,您可以轻松地仅调用一次它/将这两次调用合并到一个createObjectFactory()

Furthermore, it seems really odd to create a factor which in turn creates a factory which in turn creates another factory. 此外,创建一个因素反过来创建一个工厂,然后反过来又创建另一个工厂,似乎真的很奇怪。 Sounds like a bad design (overdesign). 听起来像是一个糟糕的设计(过度设计)。

You can call factory methods on bean instances, but in this case the factory method must not be static. 您可以在bean实例上调用工厂方法,但是在这种情况下,工厂方法不能为静态。

<bean id="myFactory2" factory-bean="myFactory" factory-method="createFactory">

</bean>

Anyway, I agree to the others. 无论如何,我同意其他人的看法。 You need to specify the requirement in detail. 您需要详细指定需求。 If your first com.myco.MyFactory1 returns an instance of com.myco.MyFactory1, it does not make much sense to call its createInstance method. 如果您的第一个com.myco.MyFactory1返回com.myco.MyFactory1的实例,则调用其createInstance方法没有多大意义。 As the same class is returned, the same static method will be called. 当返回相同的类时,将调用相同的静态方法。

If your first factory com.myco.MyFactory1 returns instances of different classes, you can use the code from above to call factory-methods on these. 如果您的第一个工厂com.myco.MyFactory1返回不同类的实例,则可以使用上面的代码在这些工厂上调用工厂方法。 But remember they have to be non static in this case. 但是请记住,在这种情况下,它们必须是非静态的。

UPDATE: 更新:

It is possible to create the new instance by calling a static method on another bean instance as follows. 可以通过在另一个bean实例上调用静态方法来创建新实例,如下所示。

 <bean id="myFactory2" class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
   <property name="targetObject"><ref local="myFactory"/></property>
   <property name="targetMethod"><value>createFactory</value></property>
 </bean>

Nevertheless you should perhaps rethink your design. 但是,您也许应该重新考虑您的设计。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM