1. 程式人生 > >Springboot系列:@SpringBootApplication註解

Springboot系列:@SpringBootApplication註解

jmx groovy sea actor via 上下 int socket @service

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

@SpringBootApplication

@SpringBootApplication源碼如下:

@Target({ElementType.TYPE})
@Retention
(RetentionPolicy.RUNTIME) @Documented @Inherited @Configuration @EnableAutoConfiguration @ComponentScan public @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;

@Configuration
public 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 {
}

註意:

  1. 使用 public 修飾 @Bean 註解的方法;
  2. 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 文件,內容如下:

# Initializers
org.springframework.context.ApplicationContextInitializer=org.springframework.boot.autoconfigure.logging.AutoConfigurationReportLoggingInitializer

# Application Listeners
org.springframework.context.ApplicationListener=org.springframework.boot.autoconfigure.BackgroundPreinitializer

# Auto Configure
org.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.OAuth2AutoConfiguration,org.springframework.boot.autoconfigure.sendgrid.SendGridAutoConfiguration,org.springframework.boot.autoconfigure.session.SessionAutoConfiguration,org.springframework.boot.autoconfigure.social.SocialWebAutoConfiguration,org.springframework.boot.autoconfigure.social.FacebookAutoConfiguration,org.springframework.boot.autoconfigure.social.LinkedInAutoConfiguration,org.springframework.boot.autoconfigure.social.TwitterAutoConfiguration,org.springframework.boot.autoconfigure.solr.SolrAutoConfiguration,org.springframework.boot.autoconfigure.velocity.VelocityAutoConfiguration,org.springframework.boot.autoconfigure.thymeleaf.ThymeleafAutoConfiguration,org.springframework.boot.autoconfigure.transaction.TransactionAutoConfiguration,org.springframework.boot.autoconfigure.transaction.jta.JtaAutoConfiguration,org.springframework.boot.autoconfigure.web.DispatcherServletAutoConfiguration,org.springframework.boot.autoconfigure.web.EmbeddedServletContainerAutoConfiguration,org.springframework.boot.autoconfigure.web.ErrorMvcAutoConfiguration,org.springframework.boot.autoconfigure.web.HttpEncodingAutoConfiguration,org.springframework.boot.autoconfigure.web.HttpMessageConvertersAutoConfiguration,org.springframework.boot.autoconfigure.web.MultipartAutoConfiguration,org.springframework.boot.autoconfigure.web.ServerPropertiesAutoConfiguration,org.springframework.boot.autoconfigure.web.WebMvcAutoConfiguration,org.springframework.boot.autoconfigure.websocket.WebSocketAutoConfiguration,org.springframework.boot.autoconfigure.websocket.WebSocketMessagingAutoConfiguration

# Template availability providers
org.springframework.boot.autoconfigure.template.TemplateAvailabilityProvider=org.springframework.boot.autoconfigure.freemarker.FreeMarkerTemplateAvailabilityProvider,org.springframework.boot.autoconfigure.mustache.MustacheTemplateAvailabilityProvider,org.springframework.boot.autoconfigure.groovy.template.GroovyTemplateAvailabilityProvider,org.springframework.boot.autoconfigure.thymeleaf.ThymeleafTemplateAvailabilityProvider,org.springframework.boot.autoconfigure.velocity.VelocityTemplateAvailabilityProvider,org.springframework.boot.autoconfigure.web.JspTemplateAvailabilityProvider

@ComponentScan

spring文檔說明:

Configures component scanning directives for use with @Configuration classes. Provides support parallel with Spring XML’s element.

為 @Configuration註解的類配置組件掃描指令。同時提供與 Spring XML’s 元素並行的支持。

Either basePackageClasses() or basePackages() (or its alias value()) may be specified to define specific packages to scan. If specific packages are not defined, scanning will occur from the package of the class that declares this annotation.

無論是 basePackageClasses() 或是 basePackages() (或其 alias 值)都可以定義指定的包進行掃描。如果指定的包沒有被定義,則將從聲明該註解的類所在的包進行掃描。

Note that the element has an annotation-config attribute; however, this annotation does not. This is because in almost all cases when using @ComponentScan, default annotation config processing (e.g. processing @Autowired and friends) is assumed. Furthermore, when using AnnotationConfigApplicationContext, annotation config processors are always registered, meaning that any attempt to disable them at the @ComponentScan level would be ignored.

註意, 元素有一個 annotation-config 屬性(詳情:http://www.cnblogs.com/exe19/p/5391712.html),但是 @ComponentScan 沒有。這是因為在使用 @ComponentScan 註解的幾乎所有的情況下,默認的註解配置處理是假定的。此外,當使用 AnnotationConfigApplicationContext, 註解配置處理器總會被註冊,以為著任何試圖在 @ComponentScan 級別是掃描失效的行為都將被忽略。

通俗的講,@ComponentScan 註解會自動掃描指定包下的全部標有 @Component註解 的類,並註冊成bean,當然包括 @Component 下的子註解@Service、@Repository、@Controller。@ComponentScan 註解沒有類似 、的屬性。

Springboot系列:@SpringBootApplication註解