SSM接口调用和IOC注入达到解耦效果

Spring面向接口调用

(1)创建Project项目
(2)配置pom.xml文件

<dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.9.RELEASE</version>
    </dependency>

Spring面向接口原理

(1)定义接口类
业务类接口(创建在com.xxx.service下)I***Service
Dao接口(创建在com.xxx.dao下)***Dao

(2)实现类
业务实现类(创建在com.xxx.service.impl下)I***ServiceImpl
Dao实现类(创建在com.xxx.Dao.impl下)***DaoImpl

(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);
    }
}

创建IPersonDao
package com.xjj.dao;

import com.xjj.domain.Person;

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

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

Spring面向接口编程-实现

1.配置文件
applicationContext.xml

  <!--指定包,spring可以将包和子包下的所有创建注解类扫描进来-->
    <!--@service
        @Controller
        @Repository
        在指定的成员变量上面加上@Autowire
    -->
    <context:component-scan base-package="com.xjj"/>

2.PersonServiceText

@Test
   public void test01(){
    //创建容器
    ClassPathXmlApplicationContext context= new ClassPathXmlApplicationContext("applicationContext.xml");
    IPersonService personService= (IPersonService) context.getBean("personService");
    System.out.println(personService);

    }

当前代码没有耦合

3.PersonServiceImpl

 package com.xjj.Service.impl;

import com.xjj.dao.impl.PersonDaoImpl;
import com.xjj.domain.Person;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.xjj.Service.IPersonService;

//类和接口是实现关系
@Service
public class PersonServiceImpl implements IPersonService {
    //等号左边接口,用接口调用方法能解决耦合度,右边用SpringMVC的注入能解决右边耦合度问题。
    @Autowired
    private PersonDaoImpl 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、付费专栏及课程。

余额充值