Spring Bean

Spring容器管理着一个或多个Bean。这些Bean是容器根据配置元数据创建出来的。在容器中,这些Bean定义被表示为BeanDefinition对象。

1、Bean命名

在容器中每个Bean必须有一个唯一的标识符,可以有多个别名。如果不指定,容器会为该Bean生成一个唯一的名称。

2、实例化Bean

  • 用构造函数进行实例化

  • 用静态工厂方法进行实例化

    <bean id="clientService" class="examples.ClientService" factory-method="ceateInstance"/>
    public class ClientService {
        private static ClientService clientService = new ClientService();
        private ClientService() {}
        
        public static ClientService createInstance() {
            return clientService;
        }
           
    }
  • 用实例工厂方法进行实例化

    <bean id="serviceLocator" class="examples.DefaultServiceLocator">
       ...
    </bean>
    ​
    <bean id="clientService" factory-bean="serviceLocator" factory-method="createClientServiceInstance"/>
    public class DefaultServiceLocator{
        private static ClientService clientService = new ClientServiceImpl();
        public ClientService createClientServiceInstance() {
            return clientService;
        }
    }
  • 确定Bean的运行时类型

BeanFactory.getType调用。

### Spring Boot 中如何定义和使用 Spring Bean #### 1. 使用 `@Component` 注解定义 Bean 可以通过在类上添加 `@Component` 注解来自动注册该类作为 Spring 容器中的一个 Bean。当启动应用时,Spring 的组件扫描机制会发现并加载带有此注解的类。 ```java import org.springframework.stereotype.Component; @Component public class MyService { public void performTask() { System.out.println("Executing task..."); } } ``` 此类会被自动检测到并实例化为名为 `myService` 的 bean[^2]。 #### 2. 配置类中使用 `@Bean` 方法定义 Bean 另一种常见的方式是在配置类里声明静态工厂方法,并在其上方加上 `@Bean` 注解。这种方式可以更灵活地控制 Bean 的创建过程以及初始化参数等。 ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @Configuration public class AppConfig { @Bean public MyRepository myRepository() { return new InMemoryMyRepository(); } private static class InMemoryMyRepository implements MyRepository { /* ... */ } } ``` 这里定义了一个名为 `myRepository` 的bean,它由 `AppConfig.myRepository()` 方法返回的对象表示. #### 3. 处理同名 Bean 覆盖的情况 如果项目中有多个地方尝试定义相同的 Bean 名称,则默认情况下会导致冲突错误。为了支持这种情况下的覆盖操作,可以在 application.properties 文件中设置属性: ```properties spring.main.allow-bean-definition-overriding=true ``` 这使得后来者能够替换掉之前已经存在的相同名字的 Bean 实例[^1].
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值