新的起点

新的起点
随笔 - 9, 文章 - 1, 评论 - 1, 引用 - 0
数据加载中……

Spring自学笔记(1)

 

用了一段时间的公司框架,还没时间认真的坐下来练习一下Spring开源框架的基础,真是有些不好意思。刚看完在网上下的关于Spring的视频教程,正好练习一下,就以水果作为今天例子程序的主角。

打开Myeclipse,添加对Spring的支持(也不知道这么选行不行,汗~)

       接下来按照默认设置直接点击Next,最后点完成即可。项目中生成了传说中功能强大的Spring配置文件applicationContext.xml,哈哈,亲一个!

       环境设置好了,接下来该编写类文件了。先生成一个Fruit接口:

1package com.haiing.myspring;
2
3public interface Fruit 
4
5{
6       //吃水果
7       public void eat();
8}

9

       接着编写实现此接口的类文件:

 1package com.haiing.myspring;
 2
 3public class Apple implements Fruit {
 4
 5  public void eat() {
 6
 7              // 吃苹果
 8
 9              System.out.println("我要吃苹果了~~~") ;       
10
11       }

12
13}

14


 1package com.haiing.myspring;
 2
 3public class potato implements Fruit 
 4{
 5       public void eat() 
 6       {
 7
 8            // 吃西红柿
 9
10              System.out.println("我要吃西红柿了~~~") ;
11       }

12}

13


 1package com.haiing.myspring;
 2
 3public class Orange implements Fruit {
 4
 5       public void eat() {
 6
 7              // 吃橘子
 8
 9              System.out.println("我要吃橘子了~~~") ;
10
11       }

12
13}

14


       接口文件写好了,现在要写测试类和配置Spring文件了。

       设置applicationContext.xml配置文件如下:

<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE beans PUBLIC "-//SPRING//DTD BEAN//EN" "http://www.springframework.org/dtd/spring-beans.dtd">

<beans>

    
<bean id="apple" class="com.haiing.myspring.Apple"></bean>

    
<bean id="potato" class="com.haiing.myspring.Potato"></bean>

    
<bean id="orange" class="com.haiing.myspring.Orange"></bean>

</beans>


       编写一个测试类文件:

 1package com.haiing.myspring;
 2
 3import org.springframework.context.ApplicationContext;
 4
 5import org.springframework.context.support.ClassPathXmlApplicationContext;
 6
 7public class TestFruit 
 8
 9{
10       public static void main(String[] args)
11       {
12
13              ApplicationContext context = null ;
14
15              context = new ClassPathXmlApplicationContext("applicationContext.xml") ;
16
17              Fruit fruit = (Fruit)context.getBean("orange") ; 
18
19              fruit.eat() ;            
20       }

21}

22

 

现在可以开始测试效果了,运行测试类,在控制台输出:

我要吃苹果了~~~

log4j:WARN No appenders could be found for logger (org.springframework.beans.factory.xml.XmlBeanDefinitionReader).

log4j:WARN Please initialize the log4j system properly.

大功告成,下面红字提示是因为没有设置日志。这样,在苹果涨价之后,我们就可以方便的修改测试文件,换成其他的水果,照吃不误了~

不过话又说回来了,换归换,吃其他的东西可是吃不出苹果的味道呀

posted on 2008-01-29 08:19 轧钢王子 阅读(276) 评论(0)  编辑  收藏 所属分类: Spring


只有注册用户登录后才能发表评论。


网站导航: