加入收藏 | 设为首页 | 会员中心 | 我要投稿 广州站长网 (https://www.020zz.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 移动互联 > 评测 > 正文

使用 Spring Framework 时常犯的十大错误

发布时间:2019-07-29 17:07:44 所属栏目:评测 来源:锅外的大佬
导读:副标题#e# Spring 可以说是最流行的 Java 框架之一,也是一只需要驯服的强大野兽。虽然它的基本概念相当容易掌握,但成为一名强大的 Spring 开发者仍需要很多时间和努力。 在本文中,我们将介绍 Spring 中一些常见的错误,特别是面向 Web 应用程序和 Spring

请注意,这些情况下,关注点分离的最佳实践要求在属性为 null 时,将其标记为有效(isValid 方法中的 s == null),如果这是属性的附加要求,则使用 @NotNull 注解。

  1. public class TopTalentData { 
  2.  @MyAnnotation(value = 10) 
  3.  @NotNull 
  4.  private String name; 
  5. }复制代码 

7. 常见错误七:(依旧)使用基于xml的配置

虽然之前版本的 Spring 需要 XML,但如今大部分配置均可通过 Java 代码或注解来完成;XML 配置只是作为附加的不必要的样板代码。

本文(及其附带的 GitHub 仓库)均使用注解来配置 Spring,Spring 知道应该连接哪些 Bean,因为待扫描的顶级包目录已在 @SpringBootApplication 复合注解中做了声明,如下所示:

  1. @SpringBootApplication 
  2. public class Application { 
  3.  public static void main(String[] args) { 
  4.  SpringApplication.run(Application.class, args); 
  5.  } 
  6. }复制代码 

复合注解(可通过 Spring 文档 了解更多信息)只是向 Spring 提示应该扫描哪些包来检索 Bean。在我们的案例中,这意味着这个顶级包 (co.kukurin)将用于检索:

  • @Component (TopTalentConverter, MyAnnotationValidator)
  • @RestController (TopTalentController)
  • @Repository (TopTalentRepository)
  • @Service (TopTalentService) 类

如果我们有任何额外的 @Configuration 注解类,它们也会检查基于 Java 的配置。

8. 常见错误八:忽略 profile

在服务端开发中,经常遇到的一个问题是区分不同的配置类型,通常是生产配置和开发配置。在每次从测试切换到部署应用程序时,不要手动替换各种配置项,更有效的方法是使用 profile。

考虑这么一种情况:你正在使用内存数据库进行本地开发,而在生产环境中使用 MySQL 数据库。本质上,这意味着你需要使用不同的 URL 和 (希望如此) 不同的凭证来访问这两者。让我们看看可以如何做到这两个不同的配置文件:

8.1. APPLICATION.YAML 文件

  1. # set default profile to 'dev' 
  2. spring.profiles.active: dev 
  3. # production database details 
  4. spring.datasource.url: 'jdbc:mysql://localhost:3306/toptal' 
  5. spring.datasource.username: root 
  6. spring.datasource.password:复制代码 

8.2. APPLICATION-DEV.YAML 文件

  1. spring.datasource.url: 'jdbc:h2:mem:' 
  2. spring.datasource.platform: h2复制代码 

假设你不希望在修改代码时意外地对生产数据库进行任何操作,因此将默认配置文件设为 dev 是很有意义的。然后,在服务器上,你可以通过提供 -Dspring.profiles.active=prod 参数给 JVM 来手动覆盖配置文件。另外,还可将操作系统的环境变量设置为所需的默认 profile。

9. 常见错误九:无法接受依赖项注入

正确使用 Spring 的依赖注入意味着允许其通过扫描所有必须的配置类来将所有对象连接在一起;这对于解耦关系非常有用,也使测试变得更为容易,而不是通过类之间的紧耦合来做这样的事情:

  1. public class TopTalentController { 
  2.  private final TopTalentService topTalentService; 
  3.  public TopTalentController() { 
  4.  this.topTalentService = new TopTalentService(); 
  5.  } 
  6. }复制代码 

我们让 Spring 为我们做连接:

  1. public class TopTalentController { 
  2.  private final TopTalentService topTalentService; 
  3.  public TopTalentController(TopTalentService topTalentService) { 
  4.  this.topTalentService = topTalentService; 
  5.  } 
  6. }复制代码 

(编辑:广州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读