技术学习:黑马程序员 JavaWeb 后端部分

MVC 架构

Controller:控制层,接收前端发送的请求,处理请求,响应数据。

Service:业务逻辑处理。

Dao:有的时候用 Mapper 表示,数据访问层(持久层),CRUD 数据。

分为三层架构实现,提高程序的扩展性和可维护性。

具体拆分示例如下,建立 controller/xxxController servoce/xxxService dao/xxxDao 三个文件将功能分开。

解耦

内聚:软件中各个功能模块 内部 的功能联系。

耦合:软件中各个层,依赖 之间 的关联程度。

软件设计原则是高内聚低耦合,比如一个用户服务类,里面就尽量只包含和用户相关的服务不要包含其他的;而几个模块之间的耦合性要尽可能低。

比如上面这个例子,controller 中 新建了一个 service 类,service 中新建了一个 dao 类。这就是耦合了。如果 service dao 中发生变化了比如换了一个其他的 service 类,那么 controller service 中也要相应地改动新建对象的部分。

我们可以通过下面这种容器思想进行进一步解耦,把 service 对象放在容器里,controller 只负责从容器中拿一个 EmpService 的对象,不用关心其怎么实现的。

依赖注入(Dependency Injection DI):容器为应用程序提供运行时所依赖的资源。

IOC DI

IOC 实现:在要放入容器的类的声明前加一句 @Component

1
2
3
4
5
@Component
public class EmpServiceA implements EmpService {}

@Component
public class EmpDaoA implements EmpDao {}

这样就指明了要将其交给容器管理,并成为 IOC 容器中的 bean。

DI 实现:在声明对象,申请 bean 的语句前加一个 @Autowired

1
2
3
4
5
6
7
8
9
10
11
12
13
public class EmpController {
@Autowired
private EmpService empService;
...
}


@Component
public class EmpServiceA implements EmpService {
@Autowired
private EmpDao empDao;
...
}

@Controller @Service @Repository 分别用于定义 Controller Service Dao 的 bean 对象,如果不属于以上三种的用 @ComponentRepository 用的比较少,一般用 mybatis 整合。

默认的 bean 对象名就是类名首字母小写,也可以自己指定 @Service(value = "serviceA") 如果只有一个参数而且是 value,可以省略 @Service("serviceA")

Warning

Springboot 集成 web 开发的时候控制器必须用 @Controller 定义。

Bean 组件扫描

其实声明完注解,要想生效,还需要被组件扫描注解 @ComponentScan 扫描到。比如 @SpringBootApplication 中默认的扫描范围是启动类所在包以及其子包。

@ComponentScan(value = "要扫描的包1", “要扫描的包2”) value 可以省略。不过不推荐这种方法,最好还是 @SpringBootApplication 而且将所有包放在启动类所在包中。

Bean 指定注入

如果容器中有多个符合条件的 bean,就无法分辨要注入哪个而报错。解决方式有以下两种:

  1. 声明默认的 bean:

    1
    2
    3
    @Component
    @Primary
    public class Dog implements Animal { ... }
  2. 在使用的时后指定要注入哪一个,这个比较常用。

    1
    2
    3
    4
    @Autowired
    @Qualifier("cat") // 可以直接声明对应类名小写,这样 Spring 就知道我们选的是哪个类。
    // 如果想自定义其他类名,需要在 @Component 里也声明对应的 value,如@Component("objectName")
    private Animal animal;
  3. @Resource

    @Resource(name = "cat")	// 不用写 Autowired 了。Resource 是 jdk 中的注解不是 Spring 中的。
    // Autowired 默认是按照类型进行注入的,而 Resource 默认是按照名称注入的
    private Animal animal;
    
    
Contact Me
  • Copyright: Copyright is owned by the author. For commercial reprints, please contact the author for authorization. For non-commercial reprints, please indicate the source.
  • Copyrights © 2022-2025 Jingqing3948

星光不问,梦终有回

LinkedIn
公众号