总结一下 Spring 中存取 Bean 的相关注解, 以及这些注解的用法.

一:对于Spring中存取Bean的相关注解有:

1.@Component:

2.@Autowired

3.@Service

4.@Repository

5.@Configuration

6.@Bean

7.@Controller

8.@Resource

二:应用场景及具体用途和用法:

应用场景:

应用分层:

1.表现层 @Controller

2.业务逻辑层 @Service

3.数据层 @Repository

4.配置层 @Configuration

5.组件 @Component

注解一些理解:

一: 1,2,3,4注解都由@Component注解衍生,所以2,3,4注解在使用时可以由@Component注解代替,但是@Controller注解是个例外,不能由@Component注解代替.

二:由于不同层级需要各自对应的注解去分层+赋能,所以才需要@Component衍生出这些注解应用在不同的场景,其实际作用一致,只是为了让人们在看到注解后可以对应知道是哪一层的代码,让代码分层更清晰,人更容易理解和维护.

三:当然除了 "让人看懂",这些派生注解还附带了少量专属的 "赋能" 功能(这是 Spring 设计它们的另一层原因,这里不仔细展开了)

具体用途:

针对Spring中的Bean,注解可分成两类:(bean的存储+bean的获取)

1.bean的存储(五大注解):@Component,@Controller,@Service,@Repository,@ Configuration

2.bean的获取:@Autowired,@Resource,@Qualifier

具体用法:

先存(Bean的存储):

1.在类前写上存储bean的注解,从而将bean对象的创建和管理,依赖关系的维护,从"程序员手动控制"交给Spring容器自动控制.

后取(Bean的获取):

2.在属性上/构造器上/Setter方法上写上获取bean的注解,从而从Spring这个IOC容器中获取到bean.

具体操作****如下:

java 复制代码
import org.springframework.stereotype.Service;

// 默认Bean名称:helloService(类名首字母小写)
@Service
public class HelloService {
    public void sayHello() {
        System.out.println("Hello! 这是Spring Boot容器中的Bean~");
    }
}



Spring Boot的核心启动+Bean的获取:
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;

@SpringBootApplication
public class MySpringBootMain {
    public static void main(String[] args) {
        // 1. 启动容器
        ApplicationContext context = SpringApplication.run(MySpringBootMain.class, args);

        // 2. 按你笔记的写法:getBean("Bean名称", Bean类型)
        // Bean名称默认是类名首字母小写 → "helloService"
        HelloService helloService = context.getBean("helloService", HelloService.class);

        // 3. 使用Bean
        helloService.sayHello();
    }
}

3.对于无法用类注解声明的Bean则需要用到@Bean注解,比如第三方类和自定义穿件逻辑的类.

注意:@Bean必须跟五大注解其一一起使用

相关推荐
彭于晏Yan1 小时前
Spring Cloud Security:Oauth2令牌存储
java·spring boot·spring cloud
不光头强1 小时前
ArrayList知识点
java·开发语言·windows
皙然2 小时前
吃透 Java 泛型
java
斌糖雪梨2 小时前
invokeBeanFactoryPostProcessors(beanFactory); 方法详解
java·后端·spring
edjxj2 小时前
PFC电路学习
单片机·学习
摇滚侠2 小时前
SpringBoot 工程,不是所有的服务都引入了 spring-boot-starter-amqp 依赖,我应该使用什么条件注解,判断配置类是否生效
java·spring boot·spring
花间相见2 小时前
【JAVA基础03】—— JDK、JRE、JVM详解及原理
java·开发语言·jvm
勿芮介2 小时前
【大模型应用】在window/linux上卸载OpenClaw
java·服务器·前端
kuntli2 小时前
Java内部类四种类型解析
java