怎么写Spring程序-古蔺大橙子建站
RELATEED CONSULTING
相关咨询
选择下列产品马上在线沟通
服务时间:8:30-17:00
你可能遇到了下面的问题
关闭右侧工具栏

新闻中心

这里有您想知道的互联网营销解决方案
怎么写Spring程序

本篇内容主要讲解“怎么写Spring程序”,感兴趣的朋友不妨来看看。本文介绍的方法操作简单快捷,实用性强。下面就让小编来带大家学习“怎么写Spring程序”吧!

创新互联是一家专注于网站建设、成都网站制作与策划设计,洋县网站建设哪家好?创新互联做网站,专注于网站建设十余年,网设计领域的专业建站公司;建站业务涵盖:洋县等地区。洋县做网站价格咨询:18982081108


         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    4.0.0

    javapub.rodert
    firstSpringProject
    1.0-SNAPSHOT    
        
            junit
            junit
            4.13
            test
        

        
            org.springframework
            spring-context
            5.2.7.RELEASE
        

        
            org.springframework
            spring-core
            5.2.7.RELEASE
        

        
            org.springframework
            spring-beans
            5.2.7.RELEASE
        


    


  • 在项目的 src 目录下创建一个名为 javapub.rodert 的包,然后在该包中创建一个名为 PersonDao 的接口,并在接口中添加一个 add() 方法
package javapub.rodert;

/**
 * @author wangshiyu rodert
 * @date 2020/7/2 20:13
 * @description
 */
public interface PersonDao {
    public void add();
}
  • 创建接口实现类 PersonDaoImpl

javapub.rodert 包下创建 PersonDao 的实现类 PersonDaoImpl

package javapub.rodert;

/**
 * @author wangshiyu rodert
 * @date 2020/7/2 20:14
 * @description
 */
public class PersonDaoImpl implements PersonDao {
    public void add() {
        System.out.println("执行成功!!!");
    }
}
  • 创建 Spring 配置文件

Spring 配置文件是整合 Spring 的核心


       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">    


  • 到现在一个 Spring 程序已经搭建完成,测试一下

新建测试类

package javapub.rodert;import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
 * @author wangshiyu rodert
 * @date 2020/7/2 20:15
 * @description
 */
public class PersonDaoTest {

    @Test
    public void test1(){
        ApplicationContext applicationContext = new ClassPathXmlApplicationContext("ApplicationContext.xml");
        PersonDao personDao = (PersonDao) applicationContext.getBean("personDao");
        personDao.add();
    }

}

返回结果:

执行成功!!!

使用 JUnit 测试运行测试方法,运行成功。在程序执行时,对象的创建并不是通过 new 一个类完成的,而是通过 Spring 容器管理实现的。这就是 Spring IoC(控制反转) 容器思想的工作机制。

指 IoC 容器使用 setter 方法注入被依赖的实例。通过调用无参构造器或无参 static 工厂方法实例化 bean 后,调用该 bean 的 setter 方法,即可实现基于 setter 的 DI。

指 IoC 容器使用构造方法注入被依赖的实例。基于构造器的 DI 通过调用带参数的构造方法实现,每个参数代表一个依赖。

到此,相信大家对“怎么写Spring程序”有了更深的了解,不妨来实际操作一番吧!这里是创新互联网站,更多相关内容可以进入相关频道进行查询,关注我们,继续学习!


分享题目:怎么写Spring程序
链接URL:http://scgulin.cn/article/iegdgj.html