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

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

发布时间:2019-07-29 17:22:21 所属栏目:移动互联 来源:锅外的大佬
导读:Spring 可以说是最风行的 Java 框架之一,也是一只必要顺从的强盛野兽。固然它的根基观念相等轻易把握,但成为一名强盛的 Spring 开拓者仍必要许多时刻和全力。 在本文中,我们将先容 Spring 中一些常见的错误,出格是面向 Web 应用措施和 Spring Boot。正

请留意,这些环境下,存眷点疏散的最佳实践要求在属性为 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. }复制代码 

(编辑:湖南网)

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

热点阅读