在静态方法中如果想要获取spring bean容器中的实例,则此静态类需要实现ApplicationContextAware接口且需要加 @Component 注解,否则ApplicationContext无法注入。

    具体代码如下:

    1. import com.nb.demo.entity.Demo;
    2. import com.nb.demo.service.IDemoService;
    3. import org.springframework.beans.BeansException;
    4. import org.springframework.context.ApplicationContext;
    5. import org.springframework.context.ApplicationContextAware;
    6. import org.springframework.stereotype.Component;
    7. import java.util.Objects;
    8. @Component
    9. public class util implements ApplicationContextAware {
    10. private static ApplicationContext applicationContext;
    11. @Override
    12. public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
    13. if (Objects.isNull(util.applicationContext)) {
    14. util.applicationContext = applicationContext;
    15. }
    16. }
    17. public static void callDemoService(Demo demo) {
    18. // 使用applicationContext获取service实例
    19. IDemoService bean = util.applicationContext.getAutowireCapableBeanFactory().getBean(IDemoService.class);
    20. bean.save(demo);
    21. }
    22. }