Springboot系列:@SpringBootApplication註解

來源:互聯網
上載者:User

在使用 Springboot 架構進行開發的時候,通常我們會在 main 函數上添加 @SpringBootApplication 註解,今天為大家解析一下 @SpringBootApplication,如有不正之處,歡迎批評指正。 @SpringBootApplication

@SpringBootApplication源碼如下:

@Target({ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@Configuration@EnableAutoConfiguration@ComponentScanpublic @interface SpringBootApplication {    Class<?>[] exclude() default {};    String[] excludeName() default {};    @AliasFor(        annotation = ComponentScan.class,        attribute = "basePackages"    )    String[] scanBasePackages() default {};    @AliasFor(        annotation = ComponentScan.class,        attribute = "basePackageClasses"    )    Class<?>[] scanBasePackageClasses() default {};}

從原始碼中得知 @SpringBootApplication 被 @Configuration、@EnableAutoConfiguration、@ComponentScan 註解所修飾,換言之 Springboot 提供了統一的註解來替代以上三個註解,簡化程式的配置。下面解釋一下各註解的功能。 @Configuration

spring文檔說明:

@Configuration is a class-level annotation indicating that an object is a source of bean definitions. @Configuration classes declare beans via public @Bean annotated methods.

@Configuration 是一個類級注釋,指示對象是一個bean定義的源。@Configuration 類通過 @bean 註解的公用方法聲明bean。

The @Bean annotation is used to indicate that a method instantiates, configures and initializes a new object to be managed by the Spring IoC container.

@Bean 注釋是用來表示一個方法執行個體化,配置和初始化是由 Spring IoC 容器管理的一個新的對象。

通俗的講 @Configuration 一般與 @Bean 註解配合使用,用 @Configuration 註解類等價與 XML 中配置 beans,用 @Bean 註解方法等價於 XML 中配置 bean。舉例說明:

XML配置代碼如下:

<beans>    <bean id = "userService" class="com.user.UserService">        <property name="userDAO" ref = "userDAO"></property>    </bean>    <bean id = "userDAO" class="com.user.UserDAO"></bean></beans>

等價於

package org.spring.com.user;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;@Configurationpublic class Config {    @Bean    public UserService getUserService(){        UserService userService = new UserService();        userService.setUserDAO(null);        return userService;    }    @Bean    public UserDAO getUserDAO(){        return new UserDAO();    }}
package org.spring.com.user;public class UserService {    private UserDAO userDAO;    public UserDAO getUserDAO() {        return userDAO;    }    public void setUserDAO(UserDAO userDAO) {        this.userDAO = userDAO;    }}
package org.spring.com.user;public class UserDAO {}

注意: 使用 public 修飾 @Bean 註解的方法; UserService、UserDAO 類無需聲明為 @Component、@Service、@Repository、@Controller;

看了以上 Java 代碼,也許有人會問了,為什麼不用 @Autowired 註解直接注入 UserDAO。我是這麼認為的 @Configuration、@Bean 更注重配置方面的內容,比如我們在 @Bean 方法中可以設定 UserDAO 類對象的特殊資訊,比如指定 transactionManager 等。 @EnableAutoConfiguration

spring文檔說明:

Enable auto-configuration of the spring Application Context, attempting to guess and configure beans that you are likely to need. Auto-configuration classes are usually applied based on your classpath and what beans you have defined.

啟用 Spring 應用程式內容相關的自動設定,試圖猜測和配置您可能需要的bean。自動設定類通常採用基於你的 classpath 和已經定義的 beans 對象進行應用。

The package of the class that is annotated with @EnableAutoConfiguration has specific significance and is often used as a ‘default’. For example, it will be used when scanning for@Entity classes. It is generally recommended that you place@EnableAutoConfiguration in a root package so that all sub-packages and classes can be searched.

被 @EnableAutoConfiguration 註解的類所在的包有特定的意義,並且作為預設配置使用。例如,當掃描 @Entity類的時候它將本使用。通常推薦將 @EnableAutoConfiguration 配置在 root 包下,這樣所有的子包、類都可以被尋找到。

Auto-configuration classes are regular Spring Configuration beans. They are located using the SpringFactoriesLoader mechanism (keyed against this class).Generally auto-configuration beans are @Conditional beans (most often using @ConditionalOnClass and @ConditionalOnMissingBean annotations).

Auto-configuration類是常規的 Spring 配置 Bean。它們使用的是 SpringFactoriesLoader 機制(以 EnableAutoConfiguration 類路徑為 key)。通常 auto-configuration beans 是 @Conditional beans(在大多數情況下配合 @ConditionalOnClass 和 @ConditionalOnMissingBean 註解進行使用)。

SpringFactoriesLoader 機制: 
SpringFactoriesLoader會查詢包含 META-INF/spring.factories 檔案的JAR。 當找到spring.factories檔案後,SpringFactoriesLoader將查詢設定檔命名的屬性。EnableAutoConfiguration的 key 值為org.springframework.boot.autoconfigure.EnableAutoConfiguration。根據此 key 對應的值進行 spring 配置。在 spring-boot-autoconfigure.jar檔案中,包含一個 spring.factories 檔案,內容如下:

# Initializersorg.springframework.context.ApplicationContextInitializer=\org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer# Application Listenersorg.springframework.context.ApplicationListener=\org.springframework.boot.autoconfigure.BackgroundPreinitializer# Auto Configureorg.springframework.boot.autoconfigure.EnableAutoConfiguration=\org.springframework.boot.autoconfigure.admin.SpringApplicationAdminJmxAutoConfiguration,\org.springframework.boot.autoconfigure.aop.AopAutoConfiguration,\org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration,\org.springframework.boot.autoconfigure.MessageSourceAutoConfiguration,\org.springframework.boot.autoconfigure.PropertyPlaceholderAutoConfiguration,\org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration,\org.springframework.boot.autoconfigure.cache.CacheAutoConfiguration,\org.springframework.boot.autoconfigure.cassandra.CassandraAutoConfiguration,\org.springframework.boot.autoconfigure.cloud.CloudAutoConfiguration,\org.springframework.boot.autoconfigure.context.ConfigurationPropertiesAutoConfiguration,\org.springframework.boot.autoconfigure.dao.PersistenceExceptionTranslationAutoConfiguration,\org.springframework.boot.autoconfigure.data.cassandra.CassandraDataAutoConfiguration,\org.springframework.boot.autoconfigure.data.cassandra.CassandraRepositoriesAutoConfiguration,\org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchAutoConfiguration,\org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchDataAutoConfiguration,\org.springframework.boot.autoconfigure.data.elasticsearch.ElasticsearchRepositoriesAutoConfiguration,\org.springframework.boot.autoconfigure.data.jpa.JpaRepositoriesAutoConfiguration,\org.springframework.boot.autoconfigure.data.mongo.MongoDataAutoConfiguration,\org.springframework.boot.autoconfigure.data.mongo.MongoRepositoriesAutoConfiguration,\org.springframework.boot.autoconfigure.data.solr.SolrRepositoriesAutoConfiguration,\org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration,\org.springframework.boot.autoconfigure.data.rest.RepositoryRestMvcAutoConfiguration,\org.springframework.boot.autoconfigure.data.web.SpringDataWebAutoConfiguration,\org.springframework.boot.autoconfigure.freemarker.FreeMarkerAutoConfiguration,\org.springframework.boot.autoconfigure.gson.GsonAutoConfiguration,\org.springframework.boot.autoconfigure.h2.H2ConsoleAutoConfiguration,\org.springframework.boot.autoconfigure.hateoas.HypermediaAutoConfiguration,\org.springframework.boot.autoconfigure.hazelcast.HazelcastAutoConfiguration,\org.springframework.boot.autoconfigure.hazelcast.HazelcastJpaDependencyAutoConfiguration,\org.springframework.boot.autoconfigure.integration.IntegrationAutoConfiguration,\org.springframework.boot.autoconfigure.jackson.JacksonAutoConfiguration,\org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration,\org.springframework.boot.autoconfigure.jdbc.JndiDataSourceAutoConfiguration,\org.springframework.boot.autoconfigure.jdbc.XADataSourceAutoConfiguration,\org.springframework.boot.autoconfigure.jdbc.DataSourceTransactionManagerAutoConfiguration,\org.springframework.boot.autoconfigure.jms.JmsAutoConfiguration,\org.springframework.boot.autoconfigure.jmx.JmxAutoConfiguration,\org.springframework.boot.autoconfigure.jms.JndiConnectionFactoryAutoConfiguration,\org.springframework.boot.autoconfigure.jms.activemq.ActiveMQAutoConfiguration,\org.springframework.boot.autoconfigure.jms.artemis.ArtemisAutoConfiguration,\org.springframework.boot.autoconfigure.jms.hornetq.HornetQAutoConfiguration,\org.springframework.boot.autoconfigure.flyway.FlywayAutoConfiguration,\org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAutoConfiguration,\org.springframework.boot.autoconfigure.jersey.JerseyAutoConfiguration,\org.springframework.boot.autoconfigure.jooq.JooqAutoConfiguration,\org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration,\org.springframework.boot.autoconfigure.mail.MailSenderAutoConfiguration,\org.springframework.boot.autoconfigure.mail.MailSenderValidatorAutoConfiguration,\org.springframework.boot.autoconfigure.mobile.DeviceResolverAutoConfiguration,\org.springframework.boot.autoconfigure.mobile.DeviceDelegatingViewResolverAutoConfiguration,\org.springframework.boot.autoconfigure.mobile.SitePreferenceAutoConfiguration,\org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoAutoConfiguration,\org.springframework.boot.autoconfigure.mongo.MongoAutoConfiguration,\org.springframework.boot.autoconfigure.mustache.MustacheAutoConfiguration,\org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration,\org.springframework.boot.autoconfigure.reactor.ReactorAutoConfiguration,\org.springframework.boot.autoconfigure.security.SecurityAutoConfiguration,\org.springframework.boot.autoconfigure.security.SecurityFilterAutoConfiguration,\org.springframework.boot.autoconfigure.security.FallbackWebSecurityAutoConfiguration,\org.springframework.boot.autoconfigure.security.oauth2

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.