第一步:新建maven 项目 FirstSpringJAVA
第二步:导入spring对应的jar包
pom.xml
org.springframework spring-context 4.3.1.RELEASE org.springframework spring-beans 4.3.1.RELEASE jar org.springframework spring-webmvc 4.3.1.RELEASE jar org.springframework spring-orm 4.3.1.RELEASE jar
第三步:声明接口
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
第七步:编写测试类
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(); }}
第八步:运行结果如下
第九步:这样就可以通过直接修改配置文件来实现解耦