我正在尝试为以下问题找到一个好的解决方案:
我在应用程序中为各种DAO配置了许多Spring bean,如:
<bean id="productDao" class="com.myproject.ProductJdbcDao">
<property name="dataSource" ref="dataSource" />
<property name="getAllProductsSql" value="SELECT * FROM ${mySchema}PRODUCT_TABLE" />
</bean>
<bean id="customerDao" class="com.myproject.CustomerJdbcDao">
<property name="dataSource" ref="dataSource" />
</bean>
在我们的属性文件中设置 mySchema ,如:
mySchema=TESTDBSCHEMA.
我还有一个配置如下的Spring bean后处理器:
<bean class="com.project.SchemaAwareBeanPostProcessor">
<property name="mySchema" value="${mySchema}" />
<property name="differentSchema" value="${differentSchema}" />
</bean>
postProcessBeforeInitialization()方法实现如下:
@Override
public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
if(bean instanceof SchemaAwareInterface) {
SchemaAwareInterface dao = (SchemaAwareInterface) bean;
dao.setSchemas(this.mySchema, this.differentSchema);
}
return bean;
}
因此,任何实现 SchemaAwareInterface 的DAO都可以在Spring创建bean时获取并存储模式值。例如, customerDao 实现可能如下所示:
public class CustomerJdbcDao extends JdbcDaoSupport implements SchemaAwareInterface {
private String mySchema;
@Override
public void setSchemas(String mySchema, String differentSchema) {
this.mySchema = mySchema;
}
public List<Customer> getCustomers() {
//code that uses this.mySchema to build dynamic SQL
}
}
现在,我希望能够在应用程序运行时随意更改 mySchema 的值,以便更新使用原始mySchema值创建的任何DAO或类以使用新值。我怎么能做到这一点?