java - 如何在 spring 中为运行时动态创建的对象注入(inject)依赖?

标签 java spring spring-boot dependency-injection factory-pattern

public class PlatformEventFactory {

    public PlatformEvent createEvent(String eventType) {
        if (eventType.equals("deployment_activity")) {
            return new UdeployEvent();
        }


        return null;
    }
}

我有一个创建 PlatformEvent 的工厂类根据事件类型键入对象。

UdeployEvent 类依赖于 private RedisTemplate<String, Object> template我想在 UdeployEvent 之后注入(inject)对象已创建。

@Component
public class UdeployEvent implements PlatformEvent {

    private RedisTemplate<String, Object> template;
    private UDeployMessage uDeployMessage;

    private static final Logger logger = LoggerFactory.getLogger(UdeployEvent.class);

    public UdeployEvent() {
        uDeployMessage = new UDeployMessage();
    }


    /*public void sendNotification() {

    }*/

    public RedisTemplate<String, Object> getTemplate() {
        return template;
    }

    @Autowired
    public void setTemplate(RedisTemplate<String, Object> template) {
        this.template = template;
        System.out.println("Injection done");
    }
}

当为 UdeployEvent 返回新对象时我得到模板的空指针异常。我相信这样做的原因是因为它不是指在 spring 启动时创建的同一个 bean。 如何在运行时为新创建的对象注入(inject)依赖项。

最佳答案

您不应手动创建组件。让Spring来做这件事。使用 ApplicationContext 获取组件实例。将自动注入(inject)所有字段:

@Component
public class PlatformEventFactory {

    @Autowired
    private ApplicationContext context;

    public PlatformEvent createEvent(String eventType) {
        if (eventType.equals("deployment_activity")) {                
            return context.getBean(UdeployEvent.class);
        }

        return null;
    }
}

要使 Spring 在每次请求时都创建 UdeployEvent 组件的新实例,请将组件的范围指定为 SCOPE_PROTOTYPE:

@Component
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class UdeployEvent implements PlatformEvent {

    private RedisTemplate<String, Object> template;

    public RedisTemplate<String, Object> getTemplate() {
        return template;
    }

    @Autowired
    public void setTemplate(RedisTemplate<String, Object> template) {
        this.template = template;
        System.out.println("Injection done");
    }

    ...
}

现在每次调用 context.getBean(UdeployEvent.class) Spring 都会创建具有完全初始化的依赖项的新组件实例。

关于java - 如何在 spring 中为运行时动态创建的对象注入(inject)依赖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43015695/

相关文章:

Javaws 启动错误的 JVM

spring - 如何在服务类中隐藏Spring数据存储库功能?

java - 如何替换 BndTools 默认启动器并更改导出文件结构

java - 为什么我的 Java 莫尔斯电码翻译器给出错误的输出?

java - 将字符串数组转换为整数数组

java - Liquibase 找不到变更日志文件

java - 关于Linux系统中运行的Spring RMI

spring - 当服务器启动时,如何在 Spring Boot 中启动服务?

java - SpringBoot WebService客户端: MultipartFile and String parameters

spring - Spring Boot Java App的Gradlew Clean构建失败