Springboot系列:@SpringBootApplication注解
在使用 Springboot 框架进行开发的时候,通常我们会在 main 函数上添加 @SpringBootApplication 注解,今天为大家解析一下 @SpringBootApplication;
@SpringBootApplication
@SpringBootApplication源码如下:
从源代码中得知 @SpringBootApplication 被 @Configuration、@EnableAutoConfiguration、@ComponentScan 注解所修饰,换言之 Springboot 提供了统一的注解来替代以上三个注解,简化程序的配置。下面解释一下各注解的功能。
@SpringBootApplication = (默认属性)@Configuration + @EnableAutoConfiguration + @ComponentScan。
- public class ApplicationMain {
- public static void main(String[] args) {
- SpringApplication.run(Application.class, args);
- }
- }
分开解释@Configuration,@EnableAutoConfiguration,@ComponentScan。
1、@Configuration:提到@Configuration就要提到他的搭档@Bean。使用这两个注解就可以创建一个简单的spring配置类,可以用来替代相应的xml配置文件。
- <beans>
- <bean id = "car" class="com.test.Car">
- <property name="wheel" ref = "wheel"></property>
- </bean>
- <bean id = "wheel" class="com.test.Wheel"></bean>
- </beans>
相当于:
- @Configuration
- public class Conf {
- @Bean
- public Car car() {
- Car car = new Car();
- car.setWheel(wheel());
- return car;
- }
- @Bean
- public Wheel wheel() {
- return new Wheel();
- }
- }
@Configuration的注解类标识这个类可以使用Spring IoC容器作为bean定义的来源。@Bean注解告诉Spring,一个带有@Bean的注解方法将返回一个对象,该对象应该被注册为在Spring应用程序上下文中的bean。
2、@EnableAutoConfiguration:能够自动配置spring的上下文,试图猜测和配置你想要的bean类,通常会自动根据你的类路径和你的bean定义自动配置。
3、@ComponentScan:会自动扫描指定包下的全部标有@Component的类,并注册成bean,当然包括@Component下的子注解@Service,@Repository,@Controller。