简体   繁体   English

指定关闭时的 bean 销毁顺序

[英]Specify bean destruction sequence on shutdown

I am currently working on a spring project and I have two beans Let's say Bean A and Bean B我目前正在开发一个 spring 项目,我有两个 bean 假设 Bean A 和 Bean B

I want to make sure我想确定

  1. Bean A is created before Bean B Bean A 在 Bean B 之前创建
  2. Bean A is destroyed after destroying Bean B销毁 Bean B 后销毁 Bean A

In simple terms, Bean A should exist for the entire lifecycle of Bean B简单来说,Bean A 应该存在于 Bean B 的整个生命周期中

Is it possible to configure this?可以这样配置吗?

Please look at below mentioned example, here Class A(Service Bean) will always be created after B as B(repository Bean) available as dependency to A, otherwise it will give exception.请看下面提到的示例,这里 Class A(Service Bean) 将始终在 B 之后创建为 B(repository Bean) 可作为 A 的依赖项,否则将给出异常。 After usage of Bean B it will be destroyed as there is not significance in storing it.使用 Bean B 后,它将被销毁,因为存储它没有意义。 That is how it is design in Framework itself and it is best approach I cannot think of scenario where it is required.这就是它在框架本身中的设计方式,这是我想不出需要它的场景的最佳方法。

Even if it is required then check out Bean Scopes as this teaches excellent way to define bean life span as per requirement.即使它是必需的,也请查看Bean Scopes ,因为它教导了根据要求定义 bean 生命周期的极好方法。 Please find documentation for bean scopes .请查找bean 范围的文档。

 @Service
    public class A{
        private B repository;
        
        @Autowired
        public A(B repository) {
            super();
            this.repository = repository;
        }
    .....//(Rest of code)
    }

    public interface B extends JpaRepository<User, Long> {
    .....//Rest of method declaration
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM