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

    }
}

运行结果

相关推荐
云烟成雨TD23 分钟前
Spring AI Alibaba 1.x 系列【5】ReactAgent 构建器深度源码解析
java·人工智能·spring
最初的↘那颗心26 分钟前
Agent 实战:构建第一个 Agent 与记忆系统设计
java·大模型·agent·spring ai·记忆系统
程序猿_极客28 分钟前
SpringBoot 三大参数注解详解:@RequestParam @RequestBody @PathVariable 区别及常用开发注解
java·spring boot·后端·面试八股文·springboot注释
小胖java32 分钟前
校园通衢公告枢纽系统
java·spring boot
Crazy________33 分钟前
docker4.8
java·开发语言·eureka
cch891837 分钟前
Laravel 2.x:早期框架的奠基之路
java·开发语言
李小枫1 小时前
webflux接收application/x-www-form-urlencoded参数
android·java·开发语言
派大星酷1 小时前
Cookie、Session、Token、JWT 原理 + 流程 + 区别 + 实战
java·网络
身如柳絮随风扬1 小时前
MyBatis 插件原理详解:从拦截器到动态代理,手写一个分页插件
java·mybatis