当我通过实例工厂方法创建 bean 时,我可以在 xml 中指定“工厂方法”的参数吗?例如,在下面的代码片段中,我可以指定我的工厂方法 createAdapter() 采用一个参数来确定实例化 bean 的确切类型。
createAdapter() --><bean id="myFactoryBean" class="..." abstract="true">
...
</bean>
<!-- The bean to be created via the factory bean -->
<bean id="exampleBean"
factory-bean="myFactoryBean"
factory-method="createAdapter"/>
我在这里有几个问题:
1) myFactoryBean 可以是抽象类吗?同时,它有一个 createAdapter 方法,该方法根据不同的输入参数返回不同的 bean?
2)工厂方法createAdapter的输入,我只能在运行时知道,不知道什么时候尝试在sprint配置中指定。
基本上,我有以下代码库,我想将其转换为 spring bean,但我不知道如何:
//abstract and factory class
public abstract class QueryAdapter
{
public static queryAdapter createAdapter(Query query) {
if (query instanceof QueryByCustomer) {
return new QueryByCustomerAdapter((QueryByCustomer)query);
} else if (query instanceOf QueryByDevice) {
return new QueryByDeviceAdapter((QueryByDevice)query);
}
}
public abstract QueryResult query();
//some other shared methods
}
//inheritated class 1
public class QueryByCustomerAdapter extends QueryAdapter
{
public QueryByCustomerAdapter(QueryByCustomer queryByCustomer) {
}
@Override
public QueryResult query() {
}
}
//inheritated class 2
public class QueryByDeviceAdapter extends QueryAdapter
{
public QueryByDeviceAdapter(QueryByDevice queryByDevice) {
}
@Override
public QueryResult query() {
}
}