是否可以使用applicationcontext获取在souce.xml文件中定义的多个dao bean?

时间:2015-11-06 07:39:11

标签: spring-mvc

我创建了一个mvc spring项目,并使用在source.xml文件中定义的applicationcontext来使用dao类。

现在我将事务应用于新创建的daoclass并在source.xml中定义它。

我可以使用applicationcontext在main中调用这两个dao类吗?如果是这样,那我该怎么做?

1 个答案:

答案 0 :(得分:0)

是的这是可能的,2个月前我是春天的新手mvc。现在我可以回答这个问题,这将有助于其他新手。

步骤1:创建包含应用程序上下文的主/主类 第2步:在resource.xml中声明每个dao,并在任何其他类或dataSource上添加它们的依赖关系。 步骤3:然后在每个适配器类(dao和控制器层之间的类)中,您可以导入此主应用程序上下文并使用它来调用多个dao。

以下是示例代码:

//主应用程序上下文代码

public class MainAdaptor 
{
    static ApplicationContext context = new ClassPathXmlApplicationContext("MySQL_DataSource.xml");   
}

// sample使用主上下文的代码,您可以在多个类中使用它

public class OrderProcessingAdapter {

    static SalesDaoImpl     salesDaoImpl    = (SalesDaoImpl)    MainAdaptor.context.getBean("SalesDaoImpl");
    static LocalityDaoImpl  localityDaoImpl = (LocalityDaoImpl) MainAdaptor.context.getBean("LocalityDaoImpl");
    static StaffDaoImpl     staffDaoImpl    = (StaffDaoImpl)    MainAdaptor.context.getBean("StaffDaoImpl");
    static ShippingInfoDaoImpl shippingInfoDaoImpl = (ShippingInfoDaoImpl)MainAdaptor.context.getBean("ShippingInfoDaoImpl");
    }

// resource.xml声明示例

<!-- Initialization for data source -->
 <bean id="dataSource" class= "org.springframework.jdbc.datasource.DriverManagerDataSource">

      <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
      <property name="url" value="jdbc:mysql://localhost:3306/grocery"></property>
      <property name="username" value="newuser"></property>
      <property name="password" value="kmsg"></property>
   </bean>

    <bean id="CarDetailsDaoImpl" class="org.kmsg.dao.daoImpl.CarDetailsDaoImpl">
         <property name="dataSource" ref="dataSource"></property>
     </bean>

     <bean id="CarTypeDaoImpl" class="org.kmsg.dao.daoImpl.CarTypeDaoImpl">
         <property name="dataSource" ref="dataSource"></property>
    </bean> 

   <bean id="CategoriesDaoImpl" class="org.kmsg.dao.daoImpl.CategoriesDaoImpl">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
</beans>

//享受它!

如果需要任何帮助,请发表评论。 感谢