如何在Spring Boot 2.7.18 中实现业务代码中动态创建并注入Bean,以便在第一次调用时由Spring管理如果尚未存在?
时间: 2025-02-23 08:33:20 浏览: 57
在Spring Boot 2.7.18中,你可以通过`@Lazy`注解和`@ConditionalOnMissingBean`注解来实现动态创建并延迟加载Bean。以下是一个示例:
```java
import org.springframework.beans.factory.annotation.Conditional;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnMissingBean(MyService.class) // 如果MyService还没有bean,才会创建
public class DynamicBeanFactory {
@Lazy // 使用懒加载,意味着Bean会在首次使用时才被实例化
private MyService myService;
public MyService getMyService() {
if (myService == null) {
// 这里编写创建MyService的具体逻辑,如JDBC连接、数据库初始化等
myService = new MyServiceImpl();
}
return myService;
}
}
```
在这个例子中,`MyService`将在第一次调用`getMyService()`时,如果它不存在,则会自动创建一个新的`MyServiceImpl`实例。`@ConditionalOnMissingBean`保证了只有当缺少该类型的bean时,工厂方法才会被执行。
阅读全文
相关推荐



















