`

first spring program

阅读更多
Spring程序
Spring Gossip: 第一个 Spring 程序
首先要取得Spring的相关档案,Spring的档案放在 SourceForge。

撰写此文时,Spring最新的版本是1.2.5,有两个下载版本,一个是spring-framework-1.2.5-with- dependencies.zip,一个是spring-framework-1.2.5.zip,with-dependencies的包括一些 ant、jakarta-commons、struts、velocity等等其它开源Java项目的相依档案,如果您也需要这些相关档案,可以下载这个版本,如果您已经有这些相关档案,则只需要下载spring-framework-1.2.5.zip这个档案。

下载zip档案并解压缩之后,在dist目录下就是使用Spring所需要的相关档案,如果下载的是with-dependencies版本,则在lib 目录中的是您可能会用到的相依档案。在dist目录下,spring-core.jar是Spring的核心,如果日后需要使用到Spring其它的子框架支持,再将其它的jar档案加入即可,例如spring-aop.jar、spring-webmvc.jar等等。您也可以直接使用 spring.jar这个档案,它包括了所有Spring支持的功能所需要的所有类别,而不再需要加入个别的jar档案。

注意在Spring 1.2之后,原先于spring-core.jar中与Bean相关的一些套件,现在已移至spring-beans.jar中。

就这边接下来要练习的第一个Spring程序,要将spring-core.jar、spring-beans.jar,以及相依的commons- logging.jar加至Classpath的路径中,您可以在lib目录的jakarta-commons目录中找到。

来撰写您的第一个组件(Component),它只是一个简单的JavaBean,用来向使用者打声招呼:

HelloBean.java
package onlyfun.caterpillar; public class HelloBean {     private String helloWord;         public void setHelloWord(String helloWord) {         this.helloWord = helloWord;     }     public String getHelloWord() {         return helloWord;     } }

稍后您可以透过setHelloWord()这个Setter来设定新的招呼语,不过并不是亲自撰写程序来作这些事,而是在组态档案定义,由Spring 来为您作设定的动作,接着可以撰写Bean的定义档案,定义档案会告诉Spring容器,如何完成相依对象的关系注入等动作,Bean定义档的名称可以自由定义,例如这边取名为beans-config.xml:

beans-config.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="helloBean"           class="onlyfun.caterpillar.HelloBean">         <property name="helloWord">            <value>Hello!Justin!</value>        </property>     </bean> </beans>

定义档中定义了JavaBean的别名与来源类别,<property>卷标中设定了希望注入至JavaBean的字符串值,撰写一个简单的示范程序:

SpringDemo.java
package onlyfun.caterpillar; import org.springframework.core.io.FileSystemResource;import org.springframework.core.io.Resource;import org.springframework.beans.factory.BeanFactory; import org.springframework.beans.factory.xml.XmlBeanFactory; public class SpringDemo {     public static void main(String[] args) {         Resource rs =             new FileSystemResource("beans-config.xml");         BeanFactory factory =             new XmlBeanFactory(rs);                 HelloBean hello =             (HelloBean) factory.getBean("helloBean");         System.out.println(hello.getHelloWord());     } }

BeanFactory是 Factory 模式 的一个实作例子,但用途更为一般,可以建立、管理不同型态的对象,由于这边所使用的Bean定义档是XML,所以使用实作BeanFactory接口的 XmlBeanFactory来作为管理Bean的实际对象,在Spring 1.2中,XmlBeanFactory只接受实作Resource接口的对象,像是ClassPathResource、 FileSystemResource、InputStreamResource、ServletContextResource、 UrlResource等,分别表示不同的档案来源对象,这边所使用的是FileSystemResource,表示指定相对路径或绝对路径来取得 Bean定义档, 同样的,如果您的Bean定义文件是位于Classpath路径中,您也可以使用ClasspPathResource来取得定义档。

这是从比较低层次的角度来使用Spring的IoC容器功能,藉由BeanFactory来读取组态档案并完成依赖的关联注入,这边的依赖是什么?指的是 HelloBean相依于String对象,透过Setter所保留的接口,使用Setter injection来完成这个依赖注入,而不是将招呼语写死在HelloBean,BeanFactory是整个Spring的重点所在,整个 Spring的核心都围绕着它,在这边使用的是XmlBeanFactory,负责读取XML组态档案,您也可以使用properties档案,这之后会再介绍。

BeanFactory读取Bean的组态设定并完成关系维护之后,可以藉由getBean()方法并指定Bean的别名来取得Bean实例,如果使用 BeanFactory的话,只有在真正需要Bean对象时,才会实际建立Bean实例,而不是在一开始建立BeanFactory时就建立Bean实例,来看看实际运行之后的效果:
2005/10/16 下午 07:14:03 org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
        信息: Loading XML bean definitions from file [C:\workspace\SpringDemo\beans-config.xml]
        Hello!Justin!

如果今天您要想改变招呼语,则只要更改beans-config.xml就可以了,不用修改主要的程序,从比较一般的角度来看,就意味着如果您想要改变一些对象之间的依赖关系,则只要修改组态档即可,而不用修改组件的任何一行程序。

分享到:
评论

相关推荐

    Spring优先计划

    文件名"spring-first-program-master"暗示了这是一个关于Spring初学者的项目,可能包含一系列的示例代码、教程和练习,帮助你从零开始掌握Spring框架。在实践中,你可以期待学习如何创建Spring Boot项目、配置Spring...

    apache-cxf-2.2.10安装包和如何配置到环境变量

    1. **创建服务**:你可以通过CXF的代码第一(Code-First)或WSDL第一(WSDL-First)的方式创建服务。Code-First是指先编写Java接口和服务实现,然后由CXF自动生成WSDL;WSDL-First则是先有一个WSDL描述,CXF根据WSDL...

    ActiveMQ in Action

    KEY POINTS The first book to focus purely on ActiveMQ Strong early demand through the Manning Early Access Program Real-world examples and in-depth walkthroughs Concise, developer-centric, In Action ...

    2024年Java高工面试题 2024年Java高工面试题 2024年Java高工面试题

    - **程序计数器(Program Counter Register)**: 当前线程所执行的字节码行号指示器。 #### 2. 栈帧结构 - **局部变量表**: 用于存储编译期可知的各种基本数据类型、对象引用等。 - **操作数栈**: 运算过程中的临时...

    MySql存储过程编程.chm

    Our First Stored Procedure Section 2.3. Variables Section 2.4. Parameters Section 2.5. Conditional Execution Section 2.6. Loops Section 2.7. Dealing with Errors Section 2.8. Interacting ...

    Java 9 Programming By Example

    The First Real Java Program - Sorting Names Optimizing the Sort - Making Code Professional Mastermind - Creating a Game Extending the Game - Run Parallel, Run Faster Making Our Game Professional - Do ...

    Java.9.Programming.By.Example.epub

    The First Real Java Program - Sorting Names Chapter 3. Optimizing The Sort - Making Code Professional Chapter 4. Mastermind - Creating A Game Chapter 5. Extending The Game - Run Parallel, Run Faster ...

    高级Java经典面试题2019

    Java内存主要分为堆内存(Heap)、方法区(Method Area)、栈内存(Stack)、程序计数器(Program Counter Register)和本地方法栈(Native Method Stack)。 #### Java堆的结构 Java堆是所有线程共享的一块内存...

    广西大学口语复试问题总结 命中率80%

    It is called the North Spring City, and it is also called the Motor City. The people like the other Northeastern people are kind and enthusiastic. No matter where I am, I love my hometown because it ...

    The_CSharp_Programming_Language_Third_Edition

    A complete technical specification of the C# programming language, the third edition differs in several ways from the first two. Most notably, of course, it has been updated to cover all the new ...

    常用电子书下载(J2EE编程方面的)

    这些书籍通常涵盖Java编程的各个方面,例如《Effective Java》、《Head First Java》等经典之作,能够帮助读者提高编程技巧和最佳实践。 4. **多线程编程**与**软件资源**:...

    PhantOm V1.25 修正

    – plug-in displays debug messages Log (Alt + L), so the first run advised to put all the options and examine the Log for errors. – tested only on Windows 2000 SP4, XP SP2. – with the plug, it is ...

    Java+MyEclipse+Tomcat (一)配置过程及jsp网站开发入门_Java_杨秀璋的专栏-CSDN博客1

    ### Java+MyEclipse+Tomcat (一)配置过程及jsp网站开发入门 #### 一、配置Tomcat 本文档将详细介绍如何配置...未来还可以探索更多高级主题,如Spring、Struts等框架的集成与使用,进一步提升开发效率和项目质量。

    中考专题复习二冠词.doc

    这包括特指的事物、上文已经提及的事物、独一无二的事物(如"the moon")、序数词前(如"the first")、形容词或副词的最高级前(如"the highest")、乐器前(如"play the piano")、普通名词构成的专有名词前(如...

    JSP程序的设计上机实验与综合实训部分实验代码.doc

    【JSP程序设计与实践】 ...在提供的实验代码中,我们可以看到几个...在实际开发中,这些技术会被更复杂的应用场景所结合,例如使用Servlet处理业务逻辑,JSTL标签库简化页面结构,或者MVC框架如Spring MVC进行分层设计。

    Kotlin - Kotlin Language Documentation 2.0.0

    The “Hello World” program is a traditional first step in learning a new programming language. Here’s how you would write it in Kotlin: ```kotlin fun main() { println("Hello, world!") } ``` This ...

    2019年一线互联网公司Java高级面试题总结

    - 程序计数器(Program Counter Register): 记录当前线程所执行的字节码的行号。 #### 2. 垃圾回收器 - **常见垃圾回收器**: - Serial: 单线程收集器。 - Parallel Scavenge/Parallel Old: 多线程收集器。 - ...

    高考英语重点词汇与例句.doc

    Spring is the season when flowers blossom and nature awakens. boost提高; A healthy diet can boost your immune system. brave勇敢的; She was brave enough to face her fears and overcome them. briefly...

Global site tag (gtag.js) - Google Analytics