08_Spring实现action调用service,service调用dao的过程

【工程截图】

 

【PersonDao.java】

package com.HigginCui.dao;

public interface PersonDao {
    public void savePerson();
}

【PersonDaoImpl.java】

package com.HigginCui.dao;

public class PersonDaoImpl implements PersonDao{
    @Override
    public void savePerson() {
        System.out.println("save Person...");
    }
}

【PersonService.java】

package com.HigginCui.Service;

public interface PersonService {
    public void savePerson();
}

【PersonServiceImpl.java】

package com.HigginCui.Service;

import com.HigginCui.dao.PersonDao;

public class PersonServiceImpl implements PersonService{
    private PersonDao personDao;
    //personDao的set方法
    public void setPersonDao(PersonDao personDao) {
        this.personDao = personDao;
    }
    @Override
    public void savePerson() {
        this.personDao.savePerson();
    }
}

【PersonAction.java】

package com.HigginCui.action;

import com.HigginCui.Service.PersonService;

public class PersonAction {
    private PersonService personService;
    //personService的set方法
    public void setPersonService(PersonService personService) {
        this.personService = personService;
    }
    public String savePerson(){
        this.personService.savePerson();
        return "saveOK...";
    }
}

【applicationContext.xml】

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:aop="http://www.springframework.org/schema/aop"
       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-2.5.xsd
           http://www.springframework.org/schema/aop 
           http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
    
    <bean id="personDao" class="com.HigginCui.dao.PersonDaoImpl"></bean>
    
    <bean id="personService" class="com.HigginCui.Service.PersonServiceImpl">
        <property name="personDao">
            <ref bean="personDao"/>
        </property>
    </bean>
    
    <bean id="personAction" class="com.HigginCui.action.PersonAction">
        <property name="personService">
            <ref bean="personService"/>
        </property>
    </bean>
</beans>

【testPerson.java】

package com.HigginCui.test;

import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.HigginCui.action.PersonAction;

public class testPerson {
    @Test
    public void test(){
        ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        PersonAction personAction=(PersonAction) context.getBean("personAction");
        String str=personAction.savePerson();
        System.out.println(str);
    }
}

【运行结果】

save Person...
saveOK...

 

【小结】

实现了完全的面向接口编程,在代码端没有必要关心一个接口的实现类是什么。

 

posted @ 2016-06-10 20:01  HigginCui  阅读(6776)  评论(0编辑  收藏  举报