ITeye博客

spring boot 注解

baggioback · 2017-11-01 10:58 · 技术 · 企业架构 · Markdown

@EnableAutoConfiguration和@SpringbootApplication注解

 

一、@EnableAutoConfiguration

1

2

3

4

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to “guess” how you <br>will want to configure Spring, based on the jar dependencies that you have added. Since spring-boot-starter-web added Tomcat and Spring MVC, <br>the auto-configuration will assume that you are developing a web application and setup Spring accordingly.<br><br>

Starters and Auto-Configuration

 

Auto-configuration is designed to work well with “Starters”, but the two concepts are not directly tied. <br>You are free to pick-and-choose jar dependencies outside of the starters and Spring Boot will still do <br>its best to auto-configure your application.

  这个注释告诉SpringBoot“猜”你将如何想配置Spring,基于你已经添加jar依赖项。如果spring-boot-starter-web已经添加Tomcat和Spring MVC,这个注释自动将假设您正在开发一个web应用程序并添加相应的spring设置。

  自动配置被设计用来和“Starters”一起更好的工作,但这两个概念并不直接相关。您可以自由挑选starter依赖项以外的jar包,springboot仍将尽力自动配置您的应用程序。

  spring通常建议我们将main方法所在的类放到一个root包下,@EnableAutoConfiguration(开启自动配置)注解通常都放到main所在类的上面,下面是一个典型的结构布局:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

com

+- example

+- myproject

+- Application.java

|

+- domain

|   +- Customer.java

|   +- CustomerRepository.java

|

+- service

|   +- CustomerService.java

|

+- web

+- CustomerController.java

  这样@EnableAutoConfiguration可以从逐层的往下搜索各个加注解的类,例如,你正在编写一个JPA程序(如果你的pom里进行了配置的话),spring会自动去搜索加了@Entity注解的类,并进行调用

二、@SpringbootApplication

   使用@SpringbootApplication注解  可以解决根类或者配置类(我自己的说法,就是main所在类)头上注解过多的问题,一个@SpringbootApplication相当于@Configuration,@EnableAutoConfiguration和 @ComponentScan 并具有他们的默认属性值

1

2

3

4

5

6

7

8

9

10

package com.example.myproject;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication //等同于 @Configuration @EnableAutoConfiguration @ComponentScanpublic

class Application {

public static void main(String[] args) {

SpringApplication.run(Application.class, args);

}

 

}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。