一步一步深入spring(1)--搭建和测试spring的开发环境
生活随笔
收集整理的這篇文章主要介紹了
一步一步深入spring(1)--搭建和测试spring的开发环境
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
1.引用jar包 到spring的網(wǎng)站上下載spring的jar包(本文是2.5.6),解壓縮后找到 使用spring必須引用的jar包 spring.jar ?commons-logging.jar 加入到工程中,項(xiàng)目結(jié)構(gòu)如圖: 2.項(xiàng)目搭建好了,來開發(fā)接口,此處我只需實(shí)現(xiàn)打印“Hello?World!”,所以我定義一個(gè)“sayHello”接口,代碼如下: 1 package com.yangyang;
2
3 public interface PersonService {
4 public void sayHello();
5
6 } View Code 4.接口開發(fā)好了,通過實(shí)現(xiàn)接口來完成打印“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、接口和實(shí)現(xiàn)都開發(fā)好了,那如何使用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 表示你這個(gè)組件的名字,class表示組件類 --> 7 7 <bean id="personService" class="com.yangyang.impl.PersonServiceImpl"></bean> 8 8 9 9 </beans> View Code?6.現(xiàn)在萬一具備,那如何獲取IoC容器并完成我們需要的功能呢?首先應(yīng)該實(shí)例化一個(gè)IoC容器,然后從容器中獲取需要的對象,然后調(diào)用接口完成我們需要的功能,代碼示例如下:
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 //讀取配置文件實(shí)例化一個(gè)IoC容器 18 ApplicationContext ctx=new ClassPathXmlApplicationContext("resources/beans.xml"); 19 //從容器中獲取Bean,注意此處完全“面向接口編程,而不是面向?qū)崿F(xiàn)” 20 PersonService personService=(PersonService) ctx.getBean("personService",PersonService.class); 21 personService.sayHello(); 22 } 23 24 } View Code7.運(yùn)行此單元測試,當(dāng)控制臺(tái)出現(xiàn)以下的信息表示spring成功配置,如圖:
轉(zhuǎn)載于:https://www.cnblogs.com/shunyang/p/3234886.html
總結(jié)
以上是生活随笔為你收集整理的一步一步深入spring(1)--搭建和测试spring的开发环境的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: POJ 1753 Flip Game
- 下一篇: poj 3207 2-sat