其他分享
首页 > 其他分享> > 如何在Spring中为在运行时动态创建的对象注入依赖项?

如何在Spring中为在运行时动态创建的对象注入依赖项?

作者:互联网

public class PlatformEventFactory {

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


        return null;
    }
}

我有一个工厂类,它根据eventType创建PlatformEvent类型对象.

UdeployEvent类依赖于私有RedisTemplate< String,Object>在创建UdeployEvent对象后我想要注入的模板.

@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返回新对象时,我得到模板的空指针异常.我相信原因是因为它不是指弹簧启动时创建的同一个bean.如何在运行时为新创建的对象注入依赖项.

解决方法:

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

@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,spring-boot,dependency-injection,factory-pattern
来源: https://codeday.me/bug/20190828/1753048.html