当前位置:首页 > 编程笔记 > 正文
已解决

Spring中Bean的理解(Java)

来自网友在路上 154854提问 提问时间:2023-11-20 15:25:20阅读次数: 54

最佳答案 问答题库548位专家为你答疑解惑

1.Bean(可以简单地理解为对象)

在 Spring Boot 2 中,IoC(Inversion of Control)容器使用 Spring Framework 的 IoC 容器,即 Spring IoC 容器。

Spring IoC 容器是 Spring Framework 的核心组件,负责创建、装配和管理应用程序中的对象(Bean)以及它们之间的依赖关系。该容器通过依赖注入(Dependency Injection)来实现对象之间的解耦和灵活配置。

在 Spring 框架中,Bean 是一个由 Spring IoC 容器管理的对象。

2.在 Spring Boot 中,默认启动类上注解了 @SpringBootApplication 注解,该注解组合了 @Configuration、@EnableAutoConfiguration和@ComponentScan。

@ComponentScan注解会让 Spring进行包扫描并将标有 @Component、@Controller、@Service、@Repository 等组件注解的类注册为 Bean。这些被注解标记的类将由 Spring Boot 的 IoC 容器进行管理和依赖注入。

3.Bean和@Bean存在一些不同:

使用@Bean注解的方法通常被放置在一个被@Configuration 注解标记的类中,表示该类是一个配置类,用于声明和定义 Spring 应用程序中的 Bean。

在 Spring 容器启动时,如果使用了 @Configuration 和 @Bean注解,Spring 容器会扫描配置类,并调用其中被 @Bean 注解标记的方法,以实例化并注册相应的 Bean。

例如,下面的代码会在Spring Boot启动时实现new MyBean()。

@Configuration
public class AppConfig {@Beanpublic MyBean myBean() {return new MyBean();}
}

4.@Autowired(可以简单理解为给对象赋值)

@Autowired 注解主要用于进行自动装配,即通过依赖注入的方式将其他 Bean 注入到当前 Bean 中。

可以在以下几种情况下使用 @Autowired:

在一个服务类中需要引用另一个组件类的实例时:

@Service
public class MyService {@Autowiredprivate OtherService otherService;// 使用otherService对象进行操作...
}

在配置类中注入其他 Bean时:

@Configuration
public class AppConfig {@Autowiredprivate OtherBean otherBean;// 其他配置及@Bean方法...
}

在构造函数中注入依赖时:

@Service
public class MyService {private final OtherService otherService;@Autowiredpublic MyService(OtherService otherService) {this.otherService = otherService;}// 使用otherService对象进行操作...
}

注意:private final OtherService otherService;只是声明了将要使用的OtherService的实例,但却没有进行实例化或赋值。通过在构造函数中使用@Autowired注解标记OtherService otherService参数,可以告诉Spring容器在初始化MyService类时,自动注入一个OtherService的实例进来,从而使得MyService类中的 otherService字段得到实际的对象实例。

查看全文

99%的人还看了

猜你感兴趣

版权申明

本文"Spring中Bean的理解(Java)":http://eshow365.cn/6-40444-0.html 内容来自互联网,请自行判断内容的正确性。如有侵权请联系我们,立即删除!