Spring入門helloSpring
1.新建一個動態web項目,file/new/dynamic web project
2.導入jar包
導入spring所需的常用jar包
可以建一個專門為spring的library,將常用的spring jar包放到裡面,方便導入
3.具體的目錄結構
(1)首先定義一個介面,HelloWorld.java,這是為bean實體準備的介面
package exForSpring;
public interface HelloWorld {
public void sayhello() ;
}
- 1
- 2
- 3
- 4
- 5
- 6
(2)編寫HelloWorld的實現類,HelloSpring
package exForSpring;
public class HelloSpring implements HelloWorld {
@Override
public void sayhello() {
// TODO Auto-generated method stub
System.out.println("hello Spring
");
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
(3)編寫HelloWorldService,它就是被注入依賴的類,注入的就是HelloSpring
package exForSpring;
public class HelloWorldService {
private HelloWorld helloWorld;
public HelloWorld getHelloWorld() {
return helloWorld;
}
public void setHelloWorld(HelloWorld helloWorld) {
this.helloWorld = helloWorld;
}
// public HelloWorldService(HelloWorld helloWorld) {
// super();
// this.helloWorld = helloWorld;
// }
// public HelloWorldService() {
// super();
// // TODO Auto-generated constructor stub
// }
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21
- 22
- 23
- 24
- 25
它有一個成員變數,HelloWorld,當創建它時會利用Spring的IOC功能自動注入這個成員變數。
(4)編寫bean配置文件,bean.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-4.2.xsd">
<bean id="helloworldspring" class="exForSpring.HelloSpring"></bean>
<bean id="helloworldservice" class="exForSpring.HelloWorldService">
<property name="helloWorld" ref="helloworldspring"></property>
</bean>
</beans>
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
裡面配置了兩個bean,HelloSpring和HelloWorldService。並為HelloWorldService通過property標籤注入依賴。
(5)編寫HelloProgram.java,這個類會從ApplicationContext中獲取HelloWorldService的實例
package exForSpring;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloProgram {
public static void main(String[] args) {
ApplicationContext context =
new ClassPathXmlApplicationContext("beans.xml");
HelloWorldService service =
(HelloWorldService) context.getBean("helloworldservice");
HelloWorld hw= service.getHelloWorld();
hw.sayhello();
}
}
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
4.運行結果
※Linux 常用基本命令 pwd mkdir
※Tengine-2.1.0的安裝與配置
TAG:程序員小新人學習 |