首页 > 解决方案 > 在组件之外使用 @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-bootautowiredspring-annotationsspring-bean

解决方案


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;
    }
}

推荐阅读