如何使用Spring全家桶

本篇内容介绍了“如何使用Spring全家桶”的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

创新互联公司专注于黎平网站建设服务及定制,我们拥有丰富的企业做网站经验。 热诚为您提供黎平营销型网站建设,黎平网站制作、黎平网页设计、黎平网站官网定制、重庆小程序开发服务,打造黎平网络公司原创品牌,更为您提供黎平网站排名全网营销落地服务。

创建 PersonDao 接口

在项目的 src 目录下创建一个名为 com.mengma.ioc 的包,download:玩转Spring全家桶,然后在该包中创建一个名为 PersonDao 的接口,并在接口中添加一个 add() 方法

  1. package com.mengma.ioc;

  2. publicinterfacePersonDao {

  3. publicvoid add();

  4. }

3. 创建接口实现类 PersonDaoImpl

在 com.mengma.ioc 包下创建 PersonDao 的实现类 PersonDaoImpl,编辑后如下所示。

 
  1. package com.mengma.ioc;

  2. publicclassPersonDaoImpl implementsPersonDao {

  3. @Override

  4. publicvoid add() {

  5. System.out.println("save()执行了...");

  6. }

  7. }

上述代码中,PersonDaoImpl 类实现了 PersonDao 接口中的 add() 方法,并且在方法调用时会执行输出语句。

4. 创建 Spring 配置文件

在 src 目录下创建 Spring 的核心配置文件 applicationContext.xml,编辑后如下所示。

 
  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <beansxmlns="http://www.springframework.org/schema/beans"

  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"

  4. xsi:schemaLocation="http://www.springframework.org/schema/beans

  5. http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

  6. <!-- 由 Spring容器创建该类的实例对象 -->

  7. <beanid="personDao" class="com.mengma.ioc.PersonDaoImpl" />

  8. </beans>

上述代码中,第 2~5 行代码是 Spring 的约束配置,第 7 行代码表示在 Spring 容器中创建一个 id 为 personDao 的 bean 实例,其中 id 表示文件中的唯一标识符,class 属性表示指定需要实例化 Bean 的实全限定类名(包名+类名)。

需要注意的是,Spring 的配置文件名称是可以自定义的,通常情况下,都会将配置文件命名为 applicationContext.xml(或 bean.xml)。

5. 编写测试类

在 com.mengma.ioc 包下创建测试类 FirstTest,并在该类中添加一个名为 test1() 的方法,编辑后如下所示。

 
  1. package com.mengma.ioc;

  2.  

  3. import org.junit.Test;

  4. import org.springframework.context.ApplicationContext;

  5. import org.springframework.context.support.ClassPathXmlApplicationContext;

  6.  

  7. publicclassFirstTest {

  8. @Test

  9. publicvoid testl() {

  10. // 定义Spring配置文件的路径

  11. String xmlPath = "applicationContext.xml";

  12. // 初始化Spring容器,加载配置文件

  13. ApplicationContext applicationContext = newClassPathXmlApplicationContext(

  14. xmlPath);

  15. // 通过容器获取personDao实例

  16. PersonDao personDao = (PersonDao) applicationContext

  17. .getBean("personDao");

  18. // 调用 personDao 的 add ()方法

  19. personDao.add();

  20. }

  21.  

  22. }

上述代码中,首先定义了 Spring 配置文件的路径,然后创建 Spring 容器,接下来通过 Spring 容器获取了 personDao 实例,最后调用实例的 save() 方法。

“如何使用Spring全家桶”的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注创新互联网站,小编将为大家输出更多高质量的实用文章!

当前题目:如何使用Spring全家桶
网站路径:https://www.cdcxhl.com/article30/podsso.html

成都网站建设公司_创新互联,为您提供品牌网站设计商城网站品牌网站建设微信公众号定制开发服务器托管

广告

声明:本网站发布的内容(图片、视频和文字)以用户投稿、用户转载内容为主,如果涉及侵权请尽快告知,我们将会在第一时间删除。文章观点不代表本网站立场,如需处理请联系客服。电话:028-86922220;邮箱:631063699@qq.com。内容未经允许不得转载,或转载时需注明来源: 创新互联

外贸网站建设