学习目标
- (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;
}
}