@SpringBootApplication 注解教程

/ Java / 没有评论 / 1336浏览

@SpringBootApplication 注解教程

Spring Boot 现在很火啊,火到你不学习,可能几年后你就被淘汰了。现在大的公司,包括一些支付,电商等小公司都在使用 Spring Boot。所以我们还是很有必要对它进行一下系统的学习。本文将介绍 @SpringBootApplication 注解的作用以及 SpringBoot 是如何运行的。

@SpringBootApplication 注解是用来来标注一个类,说明这是一个Spring Boot应类。

@SpringBootApplication 注解标记的类,并不一定需要包含 main 方法。

public class XttblogApplication {
    public static void main(String[] args) {
        // Spring应用启动起来
		// HelloWorldMainApplication 类是@SpringBootApplication标记的类。
        SpringApplication.run(HelloWorldMainApplication.class,args);
    }
}

@SpringBootApplication 注解的 HelloWorldMainApplication.class 类。

@SpringBootApplication
public class HelloWorldMainApplication {
}

也就是说 @SpringBootApplication 注解可以和 main 方法,也就是 SpringApplication.run() 方法分开。并不一定非要在一个类中。

@SpringBootApplication:Spring Boot应用标注在某个类上说明这个类是SpringBoot的主配置类,SpringBoot就应该运行这个类的main方法来启动SpringBoot应用。

@SpringBootApplication 是一个组合注解,主要包含 @SpringBootConfiguration 和 @EnableAutoConfiguration 这两个注解。

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Inherited
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan(excludeFilters = {
    @Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
    @Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public @interface SpringBootApplication {

@SpringBootApplication = @Configuration + @EnableAutoConfiguration + @ComponentScan。

@Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。

具体可以看下面的示例:

<beans>  
    <bean id = "xttblog" class="com.test.Xttblog">  
        <property name="url" ref = "test"></property>  
    </bean>  
    <bean id = "wheel" class="com.test.Test"></bean>  
</beans> 

而使用了 @Configuration 我们就可以这样写:

@Configuration  
public class Conf {  
    @Bean  
    public Xttblog getXttblog() {  
        Xttblog a = new Xttblog();  
        a.setUrl(getTest());  
        return a;  
    }  
    @Bean   
    public Test getTest() {  
        return new Test();  
    }  
} 

@Configuration的注解类标识这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。