01_Spring 入门案例
2018-01-20 本文已影响0人
小窗风雨
Spring入门案例--IoC
- 导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
- 编写实体类
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 路径下寻找约束配置说明 -->
- 编写测试类
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 的一个子接口,我们在使用时使用的是 ApplicationContext 的实现类 ClassPathXmlApplicationContext 。
Spring入门案例--DI
- 在上例的 HelloWorld 类中,添加属性和对应的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 标签
<?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标签下添加property标签 -->
<bean id="helloWorld" class="com.zhangquanli.spring.helloworld.HelloWorld">
<property name="info" value="你好"></property>
</bean>
</beans>
- 测试代码
public void test1() {
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
HelloWorld helloWorld = (HelloWorld) context.getBean("helloWorld");
helloWorld.show();//HelloWorld类中info属性已经被赋值
}
IoC 与 DI 概念对比
- IoC 控制反转,是指对象实例化权利由 Spring 容器来管理。
- DI 依赖注入,是指在 Spring 容器创建对象的过程中,对象所依赖的属性通过配置注入到对象中。