《读spring源码》2根据bean注解探索

把xml换成注解形式的配置类 用起来更加方便
在这里插入图片描述
打印结果:
在这里插入图片描述

package com.enjoy.cap1;

import com.enjoy.cap1.config.MainConfig;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class MainTest {

    public static void main(String args[]){

        ApplicationContext app = new AnnotationConfigApplicationContext(MainConfig.class);
        Person people = (Person) app.getBean("person");
        System.out.println(people.toString());
    }
}

package com.enjoy.cap1;

import com.sun.javafx.image.IntPixelGetter;
import lombok.Data;

@Data
public class Person {
    private String name;
    private Integer age;
    public Person (String name,Integer age){
        this.name = name;
        this.age = age;
    }
}

package com.enjoy.cap1.config;


import com.enjoy.cap1.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 代表config == 配置文件
 */
@Configuration
public class MainConfig {
    //给容器中配置bean
    @Bean
    public Person person(){
        return new Person("张三",22);
    }
}

发布了434 篇原创文章 · 获赞 58 · 访问量 31万+

猜你喜欢

转载自blog.csdn.net/ppwwp/article/details/103301013
今日推荐