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;
}
}
当前代码没有耦合度