spring 实现测试解耦
第一步:新建maven 项目 FirstSpringJAVA
第二步:导入spring对应的jar包
pom.xml
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.3.1.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.3.1.RELEASE</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.1.RELEASE</version> <type>jar</type> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>4.3.1.RELEASE</version> <type>jar</type> </dependency>
第三步:声明接口
People.java
package com.xuzhiwen.spring2; public interface People { public abstract void eat(); }
第四步:新建两个接口实现类
Man.java
package com.xuzhiwen.spring2; public class Man implements People{ @Override public void eat() { System.out.println("man eat()..."); } }
Woman.java
package com.xuzhiwen.spring2; public class Woman implements People{ @Override public void eat() { System.out.println("Woman eat()..."); } }
第五步:新建工厂类
SpringFactory.java
package com.xuzhiwen.spring2; public class SpringFactory { public People people; public void setPeople(People people) { this.people = people; } public People getPeople() { return people; } }
第六步: 新建spring配置文件
applicationContext.xml
<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-3.0.xsd"> <bean id="springFactory" class="com.xuzhiwen.spring2.SpringFactory"> <property name="people" ref="woman" /> </bean> <bean id="man" class="com.xuzhiwen.spring2.Man" /> <bean id="woman" class="com.xuzhiwen.spring2.Woman" /> </beans>
第七步:编写测试类
TestSpringFactory.java
package com.xuzhiwen.spring2; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; public class TestSpringFactory { public static void main(String[] args) { ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext.xml"); SpringFactory people = (SpringFactory) app.getBean("springFactory"); people.getPeople().eat(); } }
第八步:运行结果如下
第九步:这样就可以通过直接修改配置文件来实现解耦
<property name="people" ref="woman" />