您的位置:首页 > 编程语言 > Java开发

Spring笔记之一 -- 简单入门讲解HelloWorld

2014-08-01 23:42 423 查看
1、 Spring基本特征



1 .1开发spring所需要的工具

Spring的jar包

到http://www.springsource.org/download下载spring,然后进行解压缩,在解压目录中找到下面jar文件,拷贝到类路径下

--spring的核心类库 在spring文档的dist下

dist\spring.jar

--引入的第三方类库 都spring文档的lib下

lib\jakarta-commons\commons-logging.jar

如果使用了切面编程(AOP),还需要下列jar文件

lib/aspectj/aspectjweaver.jar和aspectjrt.jar

lib/cglib/cglib-nodep-2.1_3.jar

如果使用了JSR-250中的注解,如@Resource/@PostConstruct/@PreDestroy,还需要下列jar文件

lib\j2ee\common-annotations.jar

注:JSR(Java 规范请求)是指向JCP(Java Community Process)提出新增一个标准化技术规范的正式请求。任何人都可以提交JSR(Java 规范请求),以向Java平台增添新的API和服务。JSR已成为Java界的一个重要标准

1.2Spring配置文件

导入的jar包如图:



默认情况下是applicationContext.xml文件。可以建立很多xml文件,工程中一般都是这样配置的。

简单的例子:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!--
在这个配置中,spring容器要用默认的构造函数为HelloWorld创建对象
-->
<bean id="helloWorld" class="cn.spring.createobject.HelloWorld"></bean>

<!--
采用静态工厂方法创建对象
factory-method为工厂方法
-->
<bean id="helloWorld2" class="cn.spring.createobject.HelloWorldFactory" factory-method="getInstance"></bean>
</beans>

说明:

1)只要配置一个<bean> spring容器就会创建一个对象

2)spring容器是调用默认的构造函数来创建对象的

3)一个bean就代表一个类 id就是唯一标识符

1.3简单helloworld程序

spring容器

1、写一个java类

HelloWorld

2、写一个spring的配置文件

把HelloWorld这个类放入到spring容器中

3、启动spring容器

4、从spring容器中把helloWorld取出来

5、对象.方法

说明:spring容器负责创建对象,程序员不用创建对象

首先编写HelloWorld.java文件

package cn.spring.helloworld;

public class HelloWorld {
public void hello(){
System.out.println("hello world");
}
}

配置applicationContext.xml配置文件(文件的位置与HelloWorld在同一个包中)

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> <!--
beans
把一个类放入到spring容器中,该类就称为bean
-->
<!--
一个bean就代表一个类
id就是唯一标识符
-->
<bean id="helloWorld" class="cn.spring.helloworld.HelloWorld"></bean>
</beans>

利用Junit进行简单的测试 HelloWorldTest.java

package cn.spring.helloworld;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class HelloWorldTest {
@Test
public void test(){
/*
* 1、启动spring容器
* 2、从spring容器中把helloWorld拿出来
* 3、对象.方法
*/
//启动spring容器
ApplicationContext context = new ClassPathXmlApplicationContext("cn/spring/helloworld/applicationContext.xml");
HelloWorld helloWorld = (HelloWorld)context.getBean("helloWorld");
helloWorld.hello();
}
}

举个例子:spring容器就像一个电饭煲一样(煮饭的过程),只需要将洗好的米放进去电饭煲中,点击开关就可以,等到米饭煮熟,不一定要了解电饭煲是怎么将饭煮熟的。spring容器也一样,只需要在配置文件中配置bean,容器会在启动的时候会加载配置文件,将bean实例化。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: