day22--SSM之接口调用与IOC注入达到解耦效果

day22–SSM之接口调用与IOC注入达到解耦效果

学习目标

(1)Spring面向接口编程
(2)Spring和web结合
(3)Spring和junit的整合*
(4)SpringJDBCTemplate增删改查
(5)Spring的AOP*

Spring面向接口编程-创建Web项目

  • (1)创建Project Maven
  • (2)创建Module web app Maven
  • (3)设置java,reousrces,test
  • (4)配置依赖pom.xml

Spring面向接口编程-原理

(1)接口定义
业务类接口com.xxx.service.IXxxService
Dao接口 com.xxx.dao.IXxxDao
(2)实现类
com.xxx.service.impl.XxxServiceImpl
com.xxx.dao.impl. XxxDaoImpl
(3)一个接口有多个实现类,使用接口调用,将来更换实现类时,代码耦合底更低
判断方法:删除法
将来实现类对象由Spring管理,成员变量使用依赖注入

TestPersonService

public class TestPersonService {
    @Test
    public void test01(){
        //用户的一个功能 ,通常对应咱们的一个业务 方法
        //IPersonService  PersonServiceImpl
        //PersonServiceImpl  PersonServiceImpl
        //PersonServiceImpl personService = new PersonServiceImpl();
        IPersonService personService = new PersonServiceImpl();
        //调了一个login
        Person person = new Person();
        boolean flag = personService.login(person);
        System.out.println(flag);
    }
}


IPersonService

public interface IPersonService {
    boolean login(Person person);
}


PersonServiceImpl

//类跟接口是实现关系
public class PersonServiceImpl implements IPersonService {

    private IPersonDao dao = new PersonDaoImpl();
    @Override
    public boolean login(Person person) {
        //..调用dao方法
       boolean flag =  dao.findByUserNameAndPassword(person);
       return flag;
    }
}


IPersonDao

public interface IPersonDao {
     boolean findByUserNameAndPassword(Person person);
}


PersonDaoImpl

public class PersonDaoImpl implements IPersonDao {
    public boolean findByUserNameAndPassword(Person person) {
        return true;
    }
}


Spring面向接口编程-实现

(1)PersonServiceImplTest
(2)IPersonService
(3)PersonServiceImpl
(4)IPersonDao
(5)PersonDaoImpl
(6)Spring 注解 扫描
(7)Spring DI
变量等号左边使用接口调用方法,加上 spring的getBean或者注解注入 可以达成实现类的解耦

PersonServiceImplTest
当前程序与PersonServiceImpl没有耦合

    ClassPathXmlApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
        IPersonService personService = (IPersonService) context.getBean("personServiceImpl");
        System.out.println(personService);
        //调了一个login

PersonServiceImpl
当前程序与PersonDaoImpl没有耦合

//类跟接口是实现关系
@Service
public class PersonServiceImpl implements IPersonService {

    //private IPersonDao dao = new PersonDaoImpl();
    @Autowired
    private IPersonDao dao;
    @Override
    public boolean login(Person person) {
        //..调用dao方法
       boolean flag =  dao.findByUserNameAndPassword(person);
       return flag;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值