1、新建类SpringContextHolder
java
package org.example.spring_test.config;
import lombok.Getter;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
@Component
public class SpringContextHolder implements ApplicationContextAware {
@Getter
private static ApplicationContext applicationContext;
@Override
public void setApplicationContext(ApplicationContext context) {
SpringContextHolder.applicationContext = context;
}
}
2、假设测试类及其方法如下
java
package org.example.spring_test.service;
import org.springframework.stereotype.Component;
@Component
public class BusinessService {
public String sayHello() {
return "Hello World";
}
}
3、获取上下文对象,并调用方法如下:
java
@GetMapping("/hello")
public String hello(){
ApplicationContext applicationContext=SpringContextHolder.getApplicationContext();
// ApplicationContext ctx=new ClassPathXmlApplicationContext("services.xml");
// BusinessService businessService=ctx.getBean(BusinessService.class);
BusinessService businessService=applicationContext.getBean(BusinessService.class);
return businessService.sayHello();
}