Spring Study- lesson01-03-14
1、Maven环境配置
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.3</version>
</dependency>
</dependencies>
2、dao接口、实现类
package com.feijian.dao;
public interface UserDao {
void getUser();
}
package com.feijian.dao;
public class MySqlDaoImpl implements UserDao{
@Override
public void getUser() {
System.out.println("MySqlDao方法调用了");
}
}
package com.feijian.dao;
public class OracleDaoImpl implements UserDao {
@Override
public void getUser() {
System.out.println("OracleDao数据调用");
}
}
package com.feijian.dao;
public class UserDaoImpl implements UserDao{
@Override
public void getUser() {
System.out.println("UserDao实现类");
}
}
3、service层接口、实现类(调用setter方法)这样反转,不需要去程序猿更新对象,直接用户调用不同的接口即可
package com.feijian.service;
public interface UserService {
void getUser();
}
package com.feijian.service;
import com.feijian.dao.UserDao;
public class UserServiceImpl implements UserService {
private UserDao userDao ;
public void setUserDao(UserDao userDao) {
this.userDao = userDao;
}
@Override
public void getUser() {
userDao.getUser();
}
}
之前每次都是新建一个对象
private UserDao userDao ;
//private UserDao userDao1 = new UserDaoImpl();
第四步:测试
package com.feijian.service;
import com.feijian.dao.MySqlDaoImpl;
import com.feijian.dao.OracleDaoImpl;
import com.feijian.dao.UserDaoImpl;
public class MyTest {
public static void main(String[] args) {
UserService myService = new UserServiceImpl();
((UserServiceImpl) myService).setUserDao(new OracleDaoImpl());
myService.getUser();
((UserServiceImpl) myService).setUserDao(new MySqlDaoImpl());
myService.getUser();
((UserServiceImpl) myService).setUserDao(new UserDaoImpl());
myService.getUser();
}
}