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

Spring面向接口编程-原理

  • 接口定义
    业务类接口com.xxx.service.IXxxService
    Dao接口com.xxx.dao.IXxxDao
  • 实现类
    com.xxx.service.Impl.XxxServcieImpl
    com.xxx.dao.impl.XxxDaoImpl
  • 一个接口有多个实现类,使用接口调用,将来更换实现类时,代码耦合性更低
  • 如何判断
    用删除法
    将来实现类对象由Spring管理,成员变量使用依赖注入
  • 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实现方法
//接口:实现类
@Service
public class PersonServiceImpl implements IPersonService {
    
    
    //private IPersonDao dao = new PersonDaoImpl();
    @Autowired
    @Qualifier("personDaoImpl")
    private IPersonDao dao;
    @Override
    public boolean login(Person person) {
    
    
        //调用dao方法
        boolean flag = dao.findByUserNameAndPassword(person);
        return flag;
    }
}
  • dao层接口IPersonDao
 boolean findByUserNameAndPassword(Person person);
  • dao层实现方法PersonDaoImpl
@Repository
public class PersonDaoImpl implements IPersonDao {
    
    
    @Override
    public boolean findByUserNameAndPassword(Person person) {
    
    
        return true;
    }
}
  • applicationContext.xml
 <!-- 指定包,spring可以将包与子包下面的所有的有创建注解的类扫进来
    @Service
    @Controller
    @Repository
    我们需要的做的是,在指定的成中变量上面加@Autowire
    -->
    <context:component-scan base-package="com.wxx"/>

猜你喜欢

转载自blog.csdn.net/xinxin_____/article/details/109020933
今日推荐