@SpringBootApplication注解详细解释

@SpringBootApplicayion = @Configuration + @EnableAutoConfiguration + @Componentscan
并具有三者的默认属性

一、@Configurantion

1. @Configuration启动spring容器

@Configuration标注在上,相当于xml配置文件中的<beans>一堆空间配置</beans>,作用为:配置Spring容器
示例代码如下:

@Configuration
public class Application {
    //无参构造器
    public Application() {
        System.out.println("应用启动");
    }
}

public class myTest {
    @Test
    public void test01() {
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
    }
}

运行结果如下:

2. @Configuration配合@Bean注册Bean

@Bean标注在方法上,该方法可以返回某个实例,相当于xml文件中的<bean> </bean>,作用为:注册对象
示例代码如下:

public class Dog {
    public void sayHello() {
        System.out.println("hello...");
    }
}

@Configuration
public class Application {
    //无参构造器
    public Application() {
        System.out.println("应用启动");
    }
    //注册对象
    @Bean
    public Dog dog() {
        return new Dog();
    }
}

public class myTest {
    @Test
    public void test01() {
        ApplicationContext context = new AnnotationConfigApplicationContext(Application.class);
        Dog dog = (Dog)context.getBean("dog");
        dog.sayHello();
    }
}

运行结果如下:

2.1 @Bean

  1. @Bean有name属性,若是不指定name属性,则默认是类名首字母小写。
  2. @Bean注册的对象一般使用@Autowired(@Autowired相当于setter)注入,用@Qualifier指定注入Bean的名称

3. @Configuration配合@Component注册Bean

使用步骤:

  1. 在类上添加@Component注解,交给Spring容器管理。
  2. @Configuratin和@ComponentScan(basePackages = "路径")就会扫描@Component注解的类

@Component和@Bean对比:

  1. @Bean在@Configuration注解类的内部,所以不需要扫描
  2. @Component在@Configuration注解类的外部,所以@ComponentScan扫描

二、@EnableAutoConfiguration

功能:根据定义在classpath下的类,自动的给你生成一些Bean,并加载到Spring的Context中。

classpath 等价于 main/java + main/resources + 第三方jar包的根目录。

三、@ComponentScan

功能:定义扫描路径,并从路径中找出标识了需要装配的类装配到spring的bean容器中。

扫描的类:@Component、@Service、@Controller、@Repository

环环无敌大可爱😋

posted @ 2022-04-20 00:18  盐小果  阅读(667)  评论(0编辑  收藏  举报