Spring基础(4) : bean重写

@Configuration
public class Config1 {
    @Bean()
    public Person getP(){
        Person p = new Person();
        p.setName("config1 person");
        return p;
    }
}

public class Config2 {
    @Bean()
    public Person getP(){
        Person p = new Person();
        p.setName("config2 person");
        return p;
    }
}

 public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(Config1.class,Config2.class);
        Person p = context.getBean("getP",Person.class);
        System.out.println(p.getName());
    }

public class Person{
    public String name;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

打印:

config2 person

因为

 new AnnotationConfigApplicationContext(Config1.class,Config2.class);中 config2.class放在后面,等于覆盖前面的bean。

若代码改为
public static void main(String[] args){
        ApplicationContext context = new AnnotationConfigApplicationContext(Config2.class,Config1.class);
        Person p = context.getBean("getP",Person.class);
        System.out.println(p.getName());
    }

则打印:

config1 person

 
posted @ 2017-03-14 21:18  lh_cn  阅读(1004)  评论(0编辑  收藏  举报