SpringBoot 启动默认没有父子容器,只有一个容器

 

一、调试环境

依赖使用 Maven 管理,只用导入 spring-context 即可,这里的版本为 5.2.7

通常使用 spring 有两种配置方式:注解和配置文件

public static void main(String[] args) {
    ApplicationContext applicationContext = new AnnotationConfigApplicationContext(MainConfig.class);
    // ApplicationContext applicationContext = new ClassPathXmlApplicationContext("beans.xml");

    Person bean = applicationContext.getBean(Person.class);
    System.out.println(bean);

    // 打印 IOC 容器中所有 bean 的名称
    String[] namesForType = applicationContext.getBeanDefinitionNames();
    for (String name : namesForType) {
        System.out.println(name);
    }
}

两种配置方式都可以启动 IOC 容器

注解

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration // 告诉 Spring 这是一个配置类
@ComponentScan // 默认扫描当前包(com.test.config)及其子包(com.test.config.*)
public class MainConfig {

    // 给容器中注册一个 Bean,类型为返回值的类型,id 默认是用方法名作为 id
    @Bean("person123")
    public Person person() {
        return new Person("lisi", 20, "nice");
    }
}
View Code

相关文章:

  • 2021-06-07
  • 2021-11-20
  • 2022-01-20
  • 2021-10-04
  • 2021-12-05
  • 2021-09-04
  • 2021-04-28
猜你喜欢
  • 2021-10-13
  • 2022-02-20
  • 2021-07-08
  • 2021-07-30
  • 2021-11-13
  • 2021-07-19
相关资源
相似解决方案