spring小例子

第一步:打开myeclipse,建个web工程,名字叫spring_test 

第二步:添加jar包

 右击工程名,myeclipse –》add spring。。。

 选择默认的core包就行了。

 注意:如果以上操作步骤完成,你的src下没有applicationContext.xml,说名你的环境没搭好,重新建个项目,重复以上2步骤。

 如果src 目录下有applicationContext.xml文件,那下面就开始写代码了:

 首先建三个包 

1.org. interfaces 

2.org. interfaces.impl 

3.org.test 

4.在org. interfaces 写2个接口

 package org.interfaces; 

 public interface Food { 

public String eat(); 

 package org.interfaces; 

 public interface Person { 

public void eatFood(); 

 在org. interfaces.impl这里写实现的类

 package org.interfaces.impl; 

 import org.interfaces.Food; 

 public class Apple implements Food { 

 public String eat() { 

 return "正在吃苹果。。。";  

 } 

 package org.interfaces.impl; 

 import org.interfaces.Food; 

import org.interfaces.Person; 

 public class Man implements Person { 

 private Food food; 

 public Food getFood() { 

 return food; 

 } 

 public void setFood(Food food) { 

 this.food = food; 

 } 

 public void eatFood() { 

 System.out.println(food.eat()); 

 } 

 } 

 package org.interfaces.impl; 

 import org.interfaces.Food; 

 public class Orange implements Food { 

 public String eat() { 

 return "正在吃orange。。。"; 

 } 

 } 

 在org.test包里写测试类

 package org.interfaces.impl; 

 import org.interfaces.Person; 

import org.springframework.context.ApplicationContext; 

import org.springframework.context.support.ClassPathXmlApplicationContext; 

import org.springframework.context.support.FileSystemXmlApplicationContext; 

 public class Test { 

 public static void main(String[] args) { 

 //当applicationContext.xml在src下时间使用 

//ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml"); 

// Person p =(Person)context.getBean("man"); 

// p.eatFood(); 

 //在指定路径上applicationContext.xml 

ApplicationContext context = new FileSystemXmlApplicationContext("/WebRoot/WEB-INF/applicationContext.xml"); 

 Person p =(Person)context.getBean("man"); 

 p.eatFood(); 

 } 

 } 

原文地址:https://www.cnblogs.com/zhaoxd/p/3077338.html