在静态方法中如果想要获取spring bean容器中的实例,则此静态类需要实现ApplicationContextAware接口且需要加 @Component 注解,否则ApplicationContext无法注入。
具体代码如下:
import com.nb.demo.entity.Demo;
import com.nb.demo.service.IDemoService;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import java.util.Objects;
@Component
public class util implements ApplicationContextAware {
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (Objects.isNull(util.applicationContext)) {
util.applicationContext = applicationContext;
}
}
public static void callDemoService(Demo demo) {
// 使用applicationContext获取service实例
IDemoService bean = util.applicationContext.getAutowireCapableBeanFactory().getBean(IDemoService.class);
bean.save(demo);
}
}