2017-04-03 161 views
1

我新的春天引导和我只是想知道如果我需要,我现在有 在这里,他们是春季启动 - 什么注解需要

@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注解

只是想知道他们都需要或我可以排除任何这些注释?

感谢

+1

我也是Spring Boot的新手,但我认为你可能看起来不错。这里是@SpringBootAppliaction注释文档的开始 - http://docs.spring.io/autorepo/docs/spring-boot/current/reference/html/using-boot-using-springbootapplication-annotation.html –

+0

没有看到您的应用程序类所在的实际包是很难判断您是否需要更多或更少的注释。 –

回答

1

如果您结构像这样的代码:

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

ONLY需要@SpringBootApplication注释你的应用程序类。

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

所有你需要的春季启动配置JPA是包括JPA首发:

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

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

你会看到,它需要最少的注解。

1

我想这可能取决于你所需要的,因为我没有使用其中的几个在你的榜样的。我对Spring的所有“魔术”都不太熟悉,当谈到它在注释方面的幕后工作时。我有只

@SpringBootApplication 
@Configuration 
@ComponentScan 

为了完全发挥作用春天启动的应用程序,

@SpringBootApplication是识别这个应用程序是从春天启动的Spring的方式(一个后果,例如,是有没有web.xml文件)。

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

@Component告诉Spring在启动应用程序时查找“Components”。在您的应用程序中可能找到很多@Controllers,@Service等。

为了更准确和深入许多Spring的注解说明,我可以指导你:

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

这些都对注释出色的描述和示例。

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

希望有所帮助。

+0

您只需要'@SpringBootApplication',它是一个隐含所有其他元素的元注释。 – Strelok

+0

Strelok,你是对的。没有他们,我的应用程序仍然运行相同。我编辑了我的答案来承认这一点。 –

3

如果你的主要方法是位于顶层包,那么你需要的是:

@SpringBootApplication 

它会自动递归扫描你的源代码,并拿起任何@Bean的,@Component的或@Configuration

春天JPA的数据也会自动如果你使用这种起动配置:

spring-boot-starter-data-jpa