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

    }
}

运行结果

相关推荐
jiangxia_102430 分钟前
面试系列:什么是JAVA并发编程中的JUC并发工具类
java·后端
斜月36 分钟前
Springboot 项目加解密的那些事儿
spring boot·后端
草莓爱芒果39 分钟前
Spring Boot中使用Bouncy Castle实现SM2国密算法(与前端JS加密交互)
java·spring boot·算法
慕y2741 小时前
Java学习第九十三部分——RestTemplate
java·开发语言·学习
旋风菠萝1 小时前
设计模式---单例
android·java·开发语言
AI视觉网奇1 小时前
音频获取长度
java·前端·python
FC_nian2 小时前
IDEA配置(Maven)
java·maven·intellij-idea
汤姆yu2 小时前
基于springboot的快递分拣管理系统
java·spring boot·后端
衍生星球2 小时前
JSP 程序设计之 JSP 基础知识
java·web·jsp
m0_749317522 小时前
力扣-字母异位词
java·算法·leetcode·职场和发展