SpringBoot复习:(45)@Component定义的bean会被@Bean定义的同名的bean覆盖

有同名的bean需要配置:
spring.main.allow-bean-definition-overriding=true
否则报错。

package cn.edu.tju.component;

import org.springframework.stereotype.Component;

@Component
public class Person {
    private String name;
    private int age;

    {
        this.name = "nameInComponent";
        this.age =33;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

package cn.edu.tju.config;

import cn.edu.tju.component.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class PersonConfig {
    @Bean("person")
    Person getPerson(){
        Person p = new Person();
        p.setAge(23);
        p.setName("nameInBeanAnnotation");
        return  p;
    }
}

package cn.edu.tju;

import cn.edu.tju.component.Person;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;

@SpringBootApplication
public class Start {
    public static void main(String[] args) {
        ConfigurableApplicationContext context = SpringApplication.run(Start.class, args);
        Person person = context.getBean("person", Person.class);
        System.out.println(person.getName());

    }
}

运行结果
在这里插入图片描述

你可能感兴趣的:(SpringBoot,spring,boot,java,spring)