002. Spring Inversion of Control (IoC)

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日誌信息 ...
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章