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());

    }
}

运行结果

相关推荐
异常君几秒前
Java 应用中构建 Elasticsearch 多层次缓存:提升查询效率的实战方案
java·elasticsearch·架构
橘子编程16 分钟前
Maven从入门到精通指南
java·maven
wodownload217 分钟前
CS003-2-2-perfermance
java·开发语言·jvm
想用offer打牌21 分钟前
面试官拷打我线程池,我这样回答😗
java·后端·面试
真的很上进27 分钟前
2025最全TS手写题之partial/Omit/Pick/Exclude/Readonly/Required
java·前端·vue.js·python·算法·react·html5
重庆小透明32 分钟前
【从零学习JVM|第三篇】类的生命周期(高频面试题)
java·jvm·后端·学习
BAStriver41 分钟前
PKIX path building failed问题小结
java·maven
haciii1 小时前
深入理解数据库隔离级别与Spring Boot事务管理
spring boot·mysql
welsonx1 小时前
Android性能优化-Frida工具篇
java
圈圈编码1 小时前
LeetCode Hot100刷题——合并两个有序链表
java·数据结构·算法·leetcode·链表