一:对于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.

具体操作如下:

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必须跟五大注解其一一起使用

Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐