Skip to main content

非 spring context使用spring beans

在非spring bean的代码里使用autowred的spring service会出现报错

Autowired members must be defined in the valid spring bean

https://youtrack.jetbrains.com/issue/IDEA-124216/Green-code-is-yellow-Autowired-members-must-be-defined-in-the-valid-spring-bean

比如下面的ABC只是一个普通的 class, 直接使用 Autowired 会导致得到的efg其实是个null.


class ABC {

Autowired
EFG efg;
}

但是也有解决方法, 可以在调用方法里直接查询spring context里的beans, 得到需要用到的beans, 然后直接调用.

https://stackoverflow.com/questions/34587538/how-to-autowire-spring-beans-from-a-non-bean-object-created-at-runtime

You can use a BeanUtil class to get any bean that created in Springl

@Service
public class BeanUtil implements ApplicationContextAware {
private static ApplicationContext context;

@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
context = applicationContext;
}

public static <T> T getBean(Class<T> beanClass) {
return context.getBean(beanClass);
}
}

Then you can get the bean.

MyBean obj = BeanUtil.getBean(MyBean.class);