“Spring中@Component和@Bean的异同”的版本间的差异

来自姬鸿昌的知识库
跳到导航 跳到搜索
第30行: 第30行:
 
===== @Component =====
 
===== @Component =====
 
@Component 注解直接标注在类声明上面即可
 
@Component 注解直接标注在类声明上面即可
 +
 +
例:<syntaxhighlight lang="java">
 +
package org.example.bean;
 +
 +
import org.springframework.stereotype.Component;
 +
 +
@Component
 +
public class Student {
 +
 +
}
 +
</syntaxhighlight>在 Spring 中 @Component 注解通常要配合包扫描来实现,所以再定义一个配置类:<syntaxhighlight lang="java">
 +
package org.example.config;
 +
 +
import org.springframework.context.annotation.ComponentScan;
 +
 +
@ComponentScan("org.example.bean")
 +
public class AppConfig {
 +
}
 +
</syntaxhighlight>配置类上面使用 @ComponentScan,@ComponentScan 需要指定 @Component 注解所在的包的路径,这样 Spring 就会扫描指定包下面所有的实体类,并把带有 @Component 注解的实体类注册到 Spring 容器中
 +
  
 
===== @Bean =====
 
===== @Bean =====

2023年1月28日 (六) 12:53的版本

概述

@Component

表明一个类会作为组件类,并告知Spring要为这个类创建bean


@Bean

告知Spring这个方法将会返回一个对象,这个对象需要注册为Spring上下文中的bean,通常方法体中包含了最终产生bean实例的逻辑


相同点

都可以为Spring容器注册Bean对象


区别

作用对象不同

@Component

@Component 注解作用于类

@Bean

@Bean 注解作用于方法


使用方法不同

@Component

@Component 注解直接标注在类声明上面即可

例:

package org.example.bean;

import org.springframework.stereotype.Component;

@Component
public class Student {

}

在 Spring 中 @Component 注解通常要配合包扫描来实现,所以再定义一个配置类:

package org.example.config;

import org.springframework.context.annotation.ComponentScan;

@ComponentScan("org.example.bean")
public class AppConfig {
}

配置类上面使用 @ComponentScan,@ComponentScan 需要指定 @Component 注解所在的包的路径,这样 Spring 就会扫描指定包下面所有的实体类,并把带有 @Component 注解的实体类注册到 Spring 容器中


@Bean

@Bean 需要在配置类中使用,即类上需要加上 @Configuration 注解,然后在配置类中使用一个方法来自定义 bean 是如何创建的



实现不同

灵活性不同