简体   繁体   中英

Creating parameterized Spring bean configuration

Is it possible to have a parameterized bean template where in we can just fill in the place holders or pass arguments to tell what bean to refer to or what value to set?

<bean id='baseBean' abstract='true' argument='arg1'>
    <property...>
    .
    .
    <property name="tableName" value='arg1'>
</bean>
<bean id="derived1" parent='baseBean(table1)' >
    .
    .
</bean>
<bean id="derived2" parent='baseBean(table2)' >

</bean>

you can not pass this way parameter to class, work as a parameter name as tablename in your class for which you want to create a bean. ie

<bean id="ds"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    <property name="url" value="jdbc:mysql://localhost/SBS_SL_MERGE" />
    <property name="username" value="root" />
    <property name="password" value="" />
</bean>

in above example DriverManagerDataSource class having variable named as driverClassName,url,username,password you just passing value of those for parameter for refrence of that class....

If you want to refer this bean you can refer simply by passing bean id.

<bean id="transactionManager" 
      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
      <property name="dataSource"  ref="ds" /> 

   </bean>

now in above case there is a variable in DataSourceTransactionManager named as dataSource which required object of DataSourceTransactionManager with all default set values.

您可以使用PropertyPlaceholderConfigurer并在属性文件中定义bean ID,然后从那里控制它。就像我们用来配置数据库属性一样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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