zoukankan      html  css  js  c++  java
  • 一步一步深入spring(1)--搭建和测试spring的开发环境

    1.引用jar包
    到spring的网站上下载spring的jar包(本文是2.5.6),解压缩后找到
    使用spring必须引用的jar包
    spring.jar  commons-logging.jar
     加入到工程中,项目结构如图:
    2.项目搭建好了,来开发接口,此处我只需实现打印“Hello World!”,所以我定义一个“sayHello”接口,代码如下:
    1 package com.yangyang;
    2 
    3 public interface PersonService {
    4     public void sayHello();
    5 
    6 }
    View Code
    4.接口开发好了,通过实现接口来完成打印“Hello World!”功能;
     1 package com.yangyang.impl;
     2 
     3 import com.yangyang.PersonService;
     4 
     5 public class PersonServiceImpl implements PersonService{
     6 
     7     @Override
     8     public void sayHello() {
     9         // TODO Auto-generated method stub
    10         System.out.println("hello world");
    11     }
    12 
    13 }
    View Code

    5、接口和实现都开发好了,那如何使用Spring IoC容器来管理它们呢?这就需要配置文件,让IoC容器知道要管理哪些对象。让我们来看下配置文件resources/beans.xml(放到resources目录下):

    1 1 <?xml version="1.0" encoding="UTF-8"?>
    2 2 <!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN"
    3 3     "http://www.springframework.org/dtd/spring-beans.dtd">
    4 4 
    5 5 <beans>
    6 6   <!-- id 表示你这个组件的名字,class表示组件类 -->
    7 7     <bean id="personService" class="com.yangyang.impl.PersonServiceImpl"></bean>
    8 8 
    9 9 </beans>
    View Code

     6.现在万一具备,那如何获取IoC容器并完成我们需要的功能呢?首先应该实例化一个IoC容器,然后从容器中获取需要的对象,然后调用接口完成我们需要的功能,代码示例如下:

     1 package junit.test;
     2 import org.junit.BeforeClass;
     3 import org.junit.Test;
     4 import org.springframework.context.ApplicationContext;
     5 import org.springframework.context.support.ClassPathXmlApplicationContext;
     6 
     7 import com.yangyang.PersonService;
     8 
     9 public class SpringTest {
    10 
    11     @BeforeClass
    12     public static void setUpBeforeClass() throws Exception {
    13     }
    14 
    15     @Test
    16     public void instanceSpring() {
    17         //读取配置文件实例化一个IoC容器
    18         ApplicationContext ctx=new ClassPathXmlApplicationContext("resources/beans.xml");
    19         //从容器中获取Bean,注意此处完全“面向接口编程,而不是面向实现”
    20         PersonService personService=(PersonService) ctx.getBean("personService",PersonService.class);
    21         personService.sayHello();
    22     }
    23 
    24 }
    View Code

    7.运行此单元测试,当控制台出现以下的信息表示spring成功配置,如图:

    ----------------------------------------------------------------------------------------
    如果您觉得阅读本文对您有帮助,请微信扫码关注作者,与我进行交流!欢迎各位转载,转载文章之后须在文章页面明显位置给出作者和原文连接,谢谢。
  • 相关阅读:
    副本集-Replica Sets
    SpringBoot整合SpringData MongoDB
    Auth认证
    Form
    flask一些插件
    SQLAlchemy
    session
    上下文
    flask路由
    Flask中间件
  • 原文地址:https://www.cnblogs.com/shunyang/p/3234886.html
Copyright © 2011-2022 走看看