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

    }
}

运行结果

相关推荐
郝开1 天前
Spring Boot 2.7.18(最终 2.x 系列版本)1 - 技术选型:连接池技术选型对比;接口文档技术选型对比
java·spring boot·spring
小猪咪piggy1 天前
【项目】小型支付商城 MVC/DDD
java·jvm·数据库
知兀1 天前
【Spring/SpringBoot】SSM(Spring+Spring MVC+Mybatis)方案、各部分职责、与Springboot关系
java·spring boot·spring
向葭奔赴♡1 天前
Spring IOC/DI 与 MVC 从入门到实战
java·开发语言
早退的程序员1 天前
记一次 Maven 3.8.3 无法下载 HTTP 仓库依赖的排查历程
java·http·maven
向阳而生,一路生花1 天前
redis离线安装
java·数据库·redis
Tigshop开源商城系统1 天前
Tigshop 开源商城系统 php v5.1.9.1版本正式发布
java·大数据·开源·php·开源软件
2401_841495641 天前
【数据结构】基于BF算法的树种病毒检测
java·数据结构·c++·python·算法·字符串·模式匹配
little_xianzhong1 天前
三个常听到的消息/中间件MQTT RabbitMQ Kafka
java·笔记·中间件·消息队列
论迹1 天前
【Spring Cloud 微服务】-- 服务拆分原则
java·spring cloud·微服务