@Configuration+@Bean

 

配置类

// 配置类注解 告诉spring这是个配置
@Configuration
public class MyConfig {
    // 给容器注册一个bean,返回类型是方法返回值类型,beanName就是方法名称
    @Bean
    public Pet configName(){
        return new Pet("小猫",2);
    }

}

对象实体

@Data
@ToString
public class Pet {
    private String name;

    private int age;

    public Pet(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

输出打印

 public static void main(String[] args) {
        AnnotationConfigApplicationContext applicationContext = new AnnotationConfigApplicationContext(MyConfig.class);
        Pet bean = applicationContext.getBean(Pet.class);
        System.out.println(bean);

        String[] beanNamesForType = applicationContext.getBeanNamesForType(Pet.class);
        for (String name : beanNamesForType) {
            System.out.println(name);
        }
        System.out.println(beanNamesForType);
        Object configName = applicationContext.getBean("configName");
        System.out.println(configName);
    }

 

posted @ 2022-06-01 12:40  Dabo丶  阅读(65)  评论(0编辑  收藏  举报