Tip: The following is the body of this article, the following cases for reference

Implement the ApplicationContextAware interface to fetch context objects

package com.example.demo.config;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

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

    public static <T> T getBean(String beanName) {
        return (T)applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> className) {
        returnapplicationContext.getBean(className); }}Copy the code

SpringBoot starts the setApplicationContext class to get the context object

1) SpringBoot start class

package com.example.demo;

import com.example.demo.config.ApplicationContextUtil2;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.transaction.annotation.EnableTransactionManagement;

@SpringBootApplication
@EnableTransactionManagement
@MapperScan("com.example.demo.mapper")
public class DemoApplication {

	public static void main(String[] args) {
		ApplicationContext applicationContext = SpringApplication.run(DemoApplication.class, args);
		// Set objects in the context utility classApplicationContextUtil2.setApplicationContext(applicationContext); }}Copy the code

ApplicationContext ApplicationContext helper class

package com.example.demo.config;

import org.springframework.context.ApplicationContext;

public class ApplicationContextUtil2 {

    private static ApplicationContext applicationContext;

    public static void setApplicationContext(ApplicationContext context) {
        applicationContext = context;
    }

    public static <T> T getBean(String beanName) {
        return (T)applicationContext.getBean(beanName);
    }

    public static <T> T getBean(Class<T> className) {
        returnapplicationContext.getBean(className); }}Copy the code