建立第一個spring HelloWorld程式
阿新 • • 發佈:2019-02-09
什麼是spring
spring是一個輕量級的DI/IOC和AOP容器的開源框架。
DI:Dependency Injection(依賴注入)
IoC:inverse of control(控制反轉)
AOP: Aspect-Oriented Programming(面向切面程式設計)
DI指spring建立物件的過程中,將物件依賴屬性(簡單值,集合,物件)通過配置設定給該物件
IoC:控制反轉,就是將原本在程式中手動建立物件的控制權交給spring容器來做。
AOP:aop採取橫向抽取機制,將分散在各個地方的重複的程式碼提取出來,在編譯執行時將這些程式碼應用到需要執行的地方。
匯入依賴的jar包
使用spring,首先匯入jar包
spring-core 使用spring的核心jar包
spring-context
spring-beans
commons-logging
建立配置檔案
建立名為applicationContext.xml的配置檔案,使用spring.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.xsd"> <!-- bean id/name 給bean元素設定標識 id唯一,name不唯一 class 把哪一個類交給spring容器去管理 --> <bean id="helloWorld" name="hello world helloWorld2,helloWorld3;helloWorld4" class="com.teng.HelloWorld" scope="prototype"> </bean> <bean id = "hw" class="com.teng.HelloWorld" scope="prototype">
<!-- 第二種形式,通過有參構造注入,前提:必須有有參構造 index 通過引數的索引注入 type 通過引數的型別注入 --> <!-- <constructor-arg index="0" value="1"></constructor-arg> <constructor-arg index="1" value="向陽"></constructor-arg>--> <constructor-arg type="int" value="23"></constructor-arg> <constructor-arg type="java.lang.String" value="菲菲"></constructor-arg>
測試類
package com.teng;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class Test {
@org.junit.Test
public void test1(){
//spring 從spring容器中獲取物件
//讀取spring配置檔案,建立bean工廠
BeanFactory beanFactory = new ClassPathXmlApplicationContext("/applicationContext.xml");
HelloWorld hell = (HelloWorld) beanFactory.getBean("helloWorld");
HelloWorld hell1 = (HelloWorld) beanFactory.getBean("hello");
//HelloWorld hell2 = beanFactory.getBean(HelloWorld.class);
HelloWorld hell3 = beanFactory.getBean("hw",HelloWorld.class);
hell.sayHell();
}
}
beanFactory可以通過三種方法獲取物件
1,beanFactory.getBean(“id名/name名”);通過bean名獲取
2,beanFactory.getBean(物件.class);通過class獲取
3,beanFactory.getBean(“id名/name名”,物件.class);通過name+class 官方推薦