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/