spring之hello world

前言

spring 是容器框架,用于配置bean,并维护bean之间关系的框架,而bean是java中的任何一种对象 javabean/service/action/数据源./dao, ioc(控制反转 inverse of control) di( dependency injection 依赖注入),而spring的设计思想主要为单例和工厂模式,它能很好的解耦,简化开发,同时贯穿于各层。

不多说,先来一个入门案例,目的在先具体把握,最后在看细节

步骤一:创建一个web工程,同时引入两个jar包,一个是spring核心包(spring.jar)和日包(commons-logging.jar)及测试包junit;

步骤二:新建applicationContent.xml文件,该文件是spring的核心文件,先放在src目录下,里面暂时什么都不写

步骤三:编写helloworld类:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.zwl.spring;
public class Helloworld {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void sayhello(){
System.out.println("it is "+name);
}
}

这里主要通过spring自动注入name为helloworld来演示

步骤四:配置applicationContent.xml文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?xml version="1.0" encoding="utf-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<!-- bean元素的作用是,当我们的spring框架加载时候,spring就会自动的创建一个bean对象,并放入内存 ,
相当于Helloworld helloworld=new Helloworld();
helloworld.setName("helloworld!");
id:用于唯一标识该bean,
class:相应的bean所处的位置
-->
<bean id="helloworld" class="com.zwl.spring.Helloworld">
<property name="name">
<value>hello world!</value>
</property>
</bean>
</beans>

步骤五:编写工具类
因为spring也是初始化加载很耗内存,所以同样采取单例模式初始化

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.zwl.utils;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ApplicaionContextUtil {
private static ApplicationContext ac=null;
private ApplicaionContextUtil(){
}
static{
//1.得到spring 的applicationContext对象(容器对象)
ac=new ClassPathXmlApplicationContext("applicationContext.xml");
}
public static ApplicationContext getApplicationContext(){
return ac;
}
}

步骤六:编写测试类(用junit4)

1
2
3
4
5
6
@Test
public void test(){
//得到bean对象
Helloworld hello=(Helloworld) ApplicaionContextUtil.getApplicationContext().getBean("helloworld");
hello.sayhello();
}

测试结果:

it is hello world !

至此helloworld程序完成,当然这只是一个初步的认识spring是什么,事实上spring的注入远不止如此简单,但至少有一点可以明确,通过spring,可以帮我们管理,特别是结合其他开源框架,达到解耦和高效的作用。

热评文章