您的位置:首页 > 编程语言 > Java开发

002. Spring Inversion of Control (IoC)

2017-06-22 10:01 423 查看
1、创建Java项目:File -> New -> Java Project

2、引入必要jar包,项目结构如下



3、创建WorkService接口WorkService.java

package com.spring.service;

public interface WorkService {

public abstract void doWork();

}


4、实现WorkServiceImp类WorkServiceImp.java

package com.spring.service.imp;

import com.spring.service.WorkService;

public class WorkServiceImp implements WorkService {

@Override
public void doWork() {
System.out.println("WorkServiceImp do work...");
}

}


5、创建Worker类Worker.java

package com.spring.model;

import com.spring.service.WorkService;

public class Worker {

private WorkService workService = null;

public WorkService getWorkService() {
return workService;
}

public void setWorkService(WorkService workService) {
this.workService = workService;
}

public void doWork() {
workService.doWork();
}

}


6、创建spring配置文件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="workService" class="com.spring.service.imp.WorkServiceImp"></bean>
<bean id="worker" class="com.spring.model.Worker">
<property name="workService" ref="workService"></property>
</bean>

</beans>


7、创建Spring测试类SpringUnit.java

package com.spring.junit;

import org.junit.Test;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.spring.model.Worker;

public class SpringUnit {

@Test
public void test() {

ClassPathXmlApplicationContext ctx = new ClassPathXmlApplicationContext("applicationContext.xml");

Worker worker = (Worker) ctx.getBean("worker");
worker.doWork();

ctx.close();
}

}


8、测试结果

... 省略Spring日志信息 ...

WorkServiceImp do work...

... 省略Spring日志信息 ...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  spring