2017-04-03 83 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