在组件外部使用@Autowired

问题描述 投票:0回答:1

我有一个我想在我的应用程序中的不同位置使用的服务:

@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-boot autowired spring-annotations spring-bean
1个回答
0
投票

Spring只能将bean自动装配到Spring管理的类中。由于Action和MyTable类不是由Spring管理的,因此ActionListMain不能在那里自动接线。

[有一个(棘手的)解决方法,包括创建一个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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.