【问题标题】:Can a bean be a value to another bean in the Spring Framework?一个 bean 可以是 Spring Framework 中另一个 bean 的值吗?
【发布时间】:2013-06-10 14:17:58
【问题描述】:

我正在尝试学习 Spring 框架和 bean 配置,目前看来真的很酷。

我即将创建一个泛型类来包含我的所有 Mysql 函数,并且它需要包含 DataSource。我的问题是:是否可以在 bean 配置中设置数据源?

如果没有,那么我需要将类设置为单例,创建一个 init 函数并在 init 函数中执行以下操作:

    ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
    DataSource ds = (DataSource) context.getBean("dataSource");

问题是,我可以“注入”而不是这样做(如果这是正确的术语,请不要这样做) 直接在bean里吗?

这是我的 bean 配置。

<bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">  
    <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
    <property name="url" value="jdbc:mysql://localhost:3306/foo"/>  
    <property name="username" value="root"></property>  
    <property name="password" value="password"></property>  
        <property name="validationQuery" value="SELECT 1" />
    <property name="testOnBorrow" value="true" />
    <property name="testWhileIdle" value="true" />
     <property name="initialSize" value="5" />  
 </bean>   

 <bean id="bar" class="foo.bar">
   <property name="dataSource" value="<HERE_SETTING_THE_DATA_SOURCE_ABOVE>" />
 </bean>

这可能吗?

【问题讨论】:

  • 我认为这是注入的要点

标签: java spring


【解决方案1】:

您可以reference 像您的dataSource 这样的 bean。

你的班级应该有一个可以持有dataSource的成员:

package mypackage;

public class MyBean {

  private DataSource dataSource;

  public void setDataSource(DataSource dataSource) {
    this.dataSource = data.Source;
  }
}

然后你可以将dataSource bean注入这个bean:

<beans>
  <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource">
    <!-- set properties -->
  </bean>

  <bean id="myBean" class="mypackage.MyBean">
    <property name="dataSource" ref="dataSource"/>
  </bean>
</beans>

就是这样。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-06-18
    • 1970-01-01
    • 2017-09-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多