网创优客建站品牌官网
为成都网站建设公司企业提供高品质网站建设
热线:028-86922220
成都专业网站建设公司

定制建站费用3500元

符合中小企业对网站设计、功能常规化式的企业展示型网站建设

成都品牌网站建设

品牌网站建设费用6000元

本套餐主要针对企业品牌型网站、中高端设计、前端互动体验...

成都商城网站建设

商城网站建设费用8000元

商城网站建设因基本功能的需求不同费用上面也有很大的差别...

成都微信网站建设

手机微信网站建站3000元

手机微信网站开发、微信官网、微信商城网站...

建站知识

当前位置:首页 > 建站知识

如何使用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. xmlns="http://www.springframework.org/schema/beans"

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

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

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

  5. id="personDao" class="com.mengma.ioc.PersonDaoImpl" />

上述代码中,第 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全家桶
文章路径:http://bjjierui.cn/article/podsso.html