去官网下载开发包。
一,我的项目结构
二,搭建准备
导入jar包:spring.jar,commons-logging.jar,log4j-1.2.15.jar,junit-4.4.jar
日志文件放入src目录下:log4j.properties
spring配置文件放入src目录下:applicationContext.xml
三,创建HelloWorld类
将要纳入spring管理的类对象
- package com.lanhuigu.spring.action;
- public class HelloWorld {
- private String msg;
- //通过set方法注入属性值
- public void setMsg(String msg) {
- this.msg = msg;
- }
- public String getMsg() {
- return msg;
- }
- }
将HelloWorld对象纳入spring管理,创建一个惟一id为HelloWorld的bean对象
- <?xml version="1.0" encoding="UTF-8"?>
- <!--
- - Application context definition for JPetStore's business layer.
- - Contains bean references to the transaction manager and to the DAOs in
- - dataAccessContext-local/jta.xml (see web.xml's "contextConfigLocation").
- -->
- <beans xmlns="http://www.springframework.org/schema/beans"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xmlns:aop="http://www.springframework.org/schema/aop"
- 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/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
- http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
- <!-- 定义一个id为HelloWorld的bean -->
- <bean id="HelloWorld" class="com.lanhuigu.spring.action.HelloWorld">
- <!-- 将变量msg值依赖注入 -->
- <property name="msg">
- <value>HelloWorld</value>
- </property>
- </bean>
- </beans>
读取spring配置文件,根据bean对象id为HelloWorld获取HelloWorld对象,调用对象的属性方法
- package com.lanhuigu.spring.test;
- import org.junit.Test;
- import org.springframework.context.ApplicationContext;
- import org.springframework.context.support.ClassPathXmlApplicationContext;
- import com.lanhuigu.spring.impl.ISayHello;
- public class TestHelloWorld {
- @Test
- public void testMyHelloWorld(){
- //1.读取spring初始化的配置文件
- ApplicationContext acxt =
- new ClassPathXmlApplicationContext("/applicationContext.xml");
- //2.根据bean获取ISayHello实现类对象
- ISayHello sayHello = (ISayHello) acxt.getBean("sayHello");
- //3.调用接口方法
- System.out.println(sayHello.doSay());
- }
- }
六,输出结果
HelloWorld
七,总结
spring使用步骤:
(1)创建项目导入必须jar包
(2)加入日志文件log4j.properties,spring配置文件applicationContext.xml
(3)创建业务接口或类,纳入spring管理
(4)读取spring配置文件,根据bean对象id拿到我们的接口或类对象,使用