SpringBoot中获取ApplicationContext的三种方式

方式1:自动注入方式

@Autowired
private ApplicationContext applicationContext;

@Test
void test01() {
    Class aClass = applicationContext.getClass();
    System.out.println("方式1:"+aClass);
}

方式2:通过构造函数

@Component
class SpringBootApplicationContextTests {
private ApplicationContext applicationContext;

public SpringBootApplicationContextTests(ApplicationContext applicationContext) {
     this.applicationContext = applicationContext;
}

@Test
void test02() {
    Class aClass = applicationContext.getClass();
    System.out.println("方式2:" + aClass);
}
}

局限性:当前类要被Spring管理,且只能有一个构造函数。

方式3:实现spring提供的接口 ApplicationContextAware

spring 在bean 初始化后会判断是不是ApplicationContextAware的子类,调用setApplicationContext()方法, 会将容器中ApplicationContext传入进去

@SpringBootTest
class SpringBootApplicationContextTests implements ApplicationContextAware {

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;

    }

    @Test
    void test03() {
        System.out.println("方式3:" + applicationContext.getClass());
    }
}

代码详见GitHub - lizhjian/SpringBootTest  SpringBootApplicationContextTests

你可能感兴趣的:(spring,boot,后端,java)