Spring入門案例--IoC
- 導(dǎo)jar包
spring-beans-4.2.4.RELEASE.jar
spring-context-4.2.4.RELEASE.jar
spring-core-4.2.4.RELEASE.jar
spring-expression-4.2.4.RELEASE.jar
commons-logging-1.2.jar
log4j-1.2.16.jar
- 編寫實(shí)體類
public class HelloWorld {
public void show() {
System.out.println("Hello World show()");
}
}
- 編寫 applicationContext.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="helloWorld" class="com.zhangquanli.spring.helloworld.HelloWorld"/>
</beans>
<!-- 可以在 \spring\docs\spring-framework-reference\html\xsd-configuration.html 路徑下尋找約束配置說(shuō)明 -->
- 編寫測(cè)試類
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class HelloWorldTest {
@Test
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.show();
}
@Test
public void test2() {
HelloWorld helloWorld = new HelloWorld();
helloWorld.show();
}
}
// ApplicationContext 是 BeanFactory 的一個(gè)子接口喷橙,我們?cè)谑褂脮r(shí)使用的是 ApplicationContext 的實(shí)現(xiàn)類 ClassPathXmlApplicationContext 阿纤。
Spring入門案例--DI
- 在上例的 HelloWorld 類中,添加屬性和對(duì)應(yīng)的getter/setter方法
public class HelloWorld {
private String info;
public String getInfo() {
return info;
}
public void setInfo(String info) {
this.info = info;
}
public void show() {
System.out.println("Hello World" + info);
}
}
- 在 applicationContext.xml 文件中配置 property 標(biāo)簽
<?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標(biāo)簽下添加property標(biāo)簽 -->
<bean id="helloWorld" class="com.zhangquanli.spring.helloworld.HelloWorld">
<property name="info" value="你好"></property>
</bean>
</beans>
- 測(cè)試代碼
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.show();//HelloWorld類中info屬性已經(jīng)被賦值
}
IoC 與 DI 概念對(duì)比
- IoC 控制反轉(zhuǎn)窝剖,是指對(duì)象實(shí)例化權(quán)利由 Spring 容器來(lái)管理审残。
- DI 依賴注入梭域,是指在 Spring 容器創(chuàng)建對(duì)象的過(guò)程中,對(duì)象所依賴的屬性通過(guò)配置注入到對(duì)象中搅轿。