在 Spring Boot 应用程序中共享类的实例

CL4*_*L40 5 java spring spring-boot

我有一个特定的类用于与需要初始化的服务进行交互。在应用程序生命周期中,唯一有意义的地方是应用程序的启动,因为没有它,Spring 应用程序的其余部分就无法运行。我有这样做的想法:

@SpringBootApplication
public class MyApplication {
    public static void main(String[] args) {
        try {
            MyRequiredService mrs = new MyRequiredService();
            mrs.connect(); // This will throw if it fails
            run(MyApplication.class, args);
        } catch(MyException e) {
            System.out.println("Failed to connect to MyRequiredService!");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这将启动服务并尝试连接,但我有一个大问题。如何在应用程序中传递此类?我需要它在我正在编写的服务端点中的功能。

我没有看到任何明显的东西,搜索“在 Spring Boot 应用程序中传递类实例”会出现一堆不相关的主题。

在 Spring Boot 中是否有一种聪明、干净的方法来做到这一点?我为一个人为的例子道歉。该服务的名称足够独特,我不想违反任何协议。

Tod*_*odd 5

你可以让 Spring 为你做这件事。首先,您需要使用 注释您的类@Service,以便 Spring 在扫描类时会拾取它。

然后,定义一个init()方法并用 进行注释@PostConstruct。Spring将实例化你的MyRequiredService类并调用init()

@Service
public class MyRequiredService {

    @PostConstruct
    public void init() {
        connect();
    }

    public void connect() {
        // ...
    }
}
Run Code Online (Sandbox Code Playgroud)

可以从构造函数调用connect(),但我不喜欢定义可能从构造函数中抛出异常的对象。

然后,您可以MyRequiredService通过注释注入来在其他类中使用它@Autowired

@Component
public class MyOtherClass {
    private final MyRequiredService service;

    public MyOtherClass(final MyRequiredService service) {
        this.service = service;
    }

    // Other methods here.
}
Run Code Online (Sandbox Code Playgroud)

这与您上面尝试执行的操作具有相同的总体效果。如果MyRequiredService失败,应用程序将无法启动。