spring-boot - 在组件之外使用 @Autowired
问题描述
我想在我的应用程序的不同位置使用一项服务:
@Service
public class ActionListMain { /* .... */ }
首先,我想在实体上下文中使用:
@Entity
@Inheritance(strategy = InheritanceType.JOINED)
@Table(name = "myTable")
public class myTable {
@Autowired
@Transient
private static ActionListMain allActions;
/* .... */
}
我还想在其他非注释类中使用它,例如:
public class Action {
@Autowired
private ActionListMain actionListMain;
}
另一方面,我有一个 StartupComponent ,它按预期连接:
@Component
public class StartupComponent {
@Autowired
private ActionListMain actionListMain;
}
为什么它在所有其他类中都是 NULL ?
解决方案
Spring 只能将 bean 自动装配到 Spring 管理的类中。由于 Action 和 MyTable 类不是由 Spring 管理的,因此 ActionListMain 不能在那里自动装配。
有一个(hackish)解决方法,包括创建一个 Spring 管理的 bean 并在其中自动装配 applicationContext,然后从静态 applicationContext 获取 bean。
@Component
public class SpringContext implements ApplicationContextAware {
//Has to be static to have access from non-Spring-managed beans
private static ApplicationContext context;
public static <T extends Object> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
@Override
// Not static
public void setApplicationContext(ApplicationContext context) throws BeansException {
SpringContext.context = context;
}
}
推荐阅读
- powerapps - 如何使条码扫描仪的输出成为数据卡的输入
- unity3d - 使用图像标记统一区分资产
- java - 如何仅在片段可见时调用 onCreateView?
- c# - c# 使用 Adobe Reader 打印 PDF 并关闭
- postgresql - 使用 osm2pgsql 反向地理编码
- ios - GKAgentDelegate 的子类不调用 agentDidUpdate
- java - 我可以手动(在浏览器上)使用用户名和密码登录,但无法使用 HtmlUnit 通过我的批处理作业登录
- python - 从字符串 Python 正则表达式中删除撇号
- c++ - 对 CGAL 类型使用基于范围的 for 循环
- node.js - 访问 userSchema(NodeJs 和 MongoDB)中的事务时,我得到“未定义”作为输出