【问题标题】:Spring Boot - What Annotations Are NeededSpring Boot - 需要哪些注解
【发布时间】:2017-04-03 20:06:52
【问题描述】:

我是 Spring Boot 的新手,我只是想知道我是否需要我目前拥有的 main 方法上的所有注释 他们来了

    @Import(ServiceConfiguration.class)
@SpringBootApplication(scanBasePackages = {"com.myproject.rest",})
@EnableJpaRepositories({"com.myproject.dao.jpa"})
@EntityScan(basePackages = "com.myproject.domain.jpa")

ServiceConfiguration.class 类有如下注解

    @Configuration
@EnableConfigurationProperties({SlackServiceProperties.class})

我的数据库对象有@Entity 注释,我的其余类有@RestController 注释,我的服务类有@Component 注释

只是想知道它们是否都需要,或者我可以排除这些注释中的任何一个吗?

谢谢

【问题讨论】:

标签: java spring spring-boot annotations


【解决方案1】:

如果您的 main 方法位于顶级包中,那么您只需要:

@SpringBootApplication

它会自动递归地扫描你的资源并选择任何@Bean's、@Component's 或@Configuration's

如果你使用这个启动器,Spring Data JPA 也会自动配置:

spring-boot-starter-data-jpa

【讨论】:

    【解决方案2】:

    如果您像这样构建代码:

    com.myproject
     - Application.java
    com.myproject.configuration
     - ServiceConfiguration.java
     - OtherConfiguration.java
    com.myproject.dao.jpa
     - .. your repositories..
    com.myproject.domain.jpa
     - .. your @Entity classes...
    

    需要使用 @SpringBootApplication 注释您的应用程序类。

    Spring Boot 将自动扫描和配置您的所有 @Configuration、存储库、其他 @Component@Service 类。这意味着您不要需要手动配置@Import,您不需要@EnableJpaRepositories@EntityScan

    Spring Boot 配置 JPA 所需要的只是包含 JPA 启动器:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
    

    您可以按照本教程进行操作:https://spring.io/guides/gs/accessing-data-jpa/

    您会发现它需要最少的注释。

    【讨论】:

      【解决方案3】:

      我认为这可能取决于您的需求,因为在您的示例中我没有使用其中的一些。当涉及到使用注释的幕后工作时,我对 Spring 的所有“魔法”都不太熟悉。我有一个运行良好的 Spring Boot 应用程序,只有

      @SpringBootApplication
      @Configuration
      @ComponentScan
      

      按顺序,

      @SpringBootApplication 是 Spring 识别此应用程序来自 Spring Boot 的方式(一个结果,例如,没有 web.xml 文件)。

      @Configuration 告诉 Spring 在您的 src 路径中查找 .properties 文件。例如,在这里,您可以定义一个“application.properties”文件来定义您的数据源(供 Spring 使用的数据库信息)。

      @Component 告诉 Spring 在启动应用程序时查找“组件”。几乎可以在整个应用程序中找到 @Controllers、@Service 等。

      对于Spring的很多注解更准确、更深入的解释,我可以指导你:

      http://www.techferry.com/articles/spring-annotations.htmlhttps://dzone.com/refcardz/spring-annotations

      这些都有很好的注释描述和示例。

      编辑: @Configuration 和 @ComponentScan 包含在 @SpringBootApplication 中,正如 Strelok 在 cmets 中指出的那样。

      希望对您有所帮助。

      【讨论】:

      • 你只需要@SpringBootApplication,它是一个meta annotation,它暗示了所有其他的。
      • Strelok,你是对的。没有它们,我的应用程序仍然可以正常工作。我已经编辑了我的答案以确认这一点。
      猜你喜欢
      • 2012-02-10
      • 1970-01-01
      • 2020-03-09
      • 2017-01-07
      • 2019-12-18
      • 2012-11-21
      • 2021-10-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多