面试官:为什么要用 Spring?它到底解决了什么问题?
AI全套:Python3+TensorFlow打造人脸识别智能小程序
最新人工智能资料-Google工程师亲授 Tensorflow-入门到进阶
黑马头条项目 - Java Springboot2.0(视频、资料、代码和讲义)14天完整版
为什么要用 Spring?它到底解决了什么问题?
方式一:传统方式
1.Service层
/**
 * @author :Prannt
 * @description :Service层
 * @program : Test
 */
public class UserService {
    public void add(){
        System.out.println("service add...");
        UserDao dao = new UserDaoImpl();
        dao.query();
    }
}
2.UserDao接口
/**
 * @description :接口中只有一个抽象方法
 */
public interface UserDao {
    void query();
}
3.UserDao接口的实现类
/**
 * @description :接口的实现类,重写 query方法
 */
public class UserDaoImpl implements UserDao{
    @Override
    public void query() {
        System.out.println("dao query...");
    }
}
//测试
public class test {
    @Test
    public void test1(){
        UserService service = new UserService();
        service.add();
    }
}结论一:由以上过程可以看出,在UserService类中直接调用实现类的query方法,一旦实现类出问题,UserService立即报错,具有高度的耦合性
方式二:Spring注入对象
1.xml文件配置bean
" linktype="text" imgurl="" imgdata="null" tab="innerlink" data-linktype="2" wah-hotarea="click" style="outline: 0px; -webkit-tap-highlight-color: rgba(0, 0, 0, 0); cursor: pointer; max-width: 100%; box-sizing: border-box !important; overflow-wrap: break-word !important;"> "1.0" encoding="UTF-8"?>"http://www.springframework.org/schema/beans" 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
"userService" class="Service.UserService"> 
"dao" ref="Dao"> 
"Dao" class="Dao.UserDaoImpl"> 
2.Service层
import Dao.UserDao;
/**
 * @author :Prannt
 * @description :
 * @program : Demo01
 */
public class UserService {
    public void add(){
        System.out.println("service add......");
        dao.update();
    }
    //创建dao类型的属性,生成对应的set方法
    private UserDao dao;
    public void setDao(UserDao dao) {
        this.dao = dao;
    }
}
3.UserDao接口
public interface UserDao {
    void update();
}
4.接口的实现类
public class UserDaoImpl implements UserDao{
    @Override
    public void update() {
        System.out.println("Dao update......");
    }
}import Service.UserService;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class TestBean {
    @Test
    public void testBean(){
        ApplicationContext context = new ClassPathXmlApplicationContext("bean2.xml");
        UserService userService = context.getBean("userService",UserService.class);
        userService.add();
    }
}
结论二:观察以上过程,在UserService类中,没有直接new实现类,而是通过将Dao注入外部配置文件中的方式,使用“第三方文件”来达到解耦的目的。
总结


全栈架构社区交流群 
「全栈架构社区」建立了读者架构师交流群,大家可以添加小编微信进行加群。欢迎有想法、乐于分享的朋友们一起交流学习。
Flutter 移动应用开发实战 视频(开发你自己的抖音APP) Java面试进阶训练营 第2季(分布式篇) Java高级 - 分布式系统开发技术视频 
评论
