1. 程式人生 > 實用技巧 >Spring 獲取Bean ApplicationContextAware的使用

Spring 獲取Bean ApplicationContextAware的使用

建立類繼承ApplicationContextAware

package net.ybclass.online_ybclass.utils;

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

/**
 * @ClassName:AppUtil
 * @Description:獲取bean工具類
 * @Author:chenyb
 * @Date:2020/8/20 11:39 上午
 * @Versiion:1.0
 
*/ @Component public class AppUtil implements ApplicationContextAware { private static ApplicationContext applicationContext; @Override public void setApplicationContext(ApplicationContext args) throws BeansException { this.applicationContext=args; } public static Object getObject(String id){
return applicationContext.getBean(id); } }

使用

@RestController
public class TestController {
    @GetMapping("test")
    public JsonData test()
    {
        VideoService videoService= (VideoService)AppUtil.getObject("videoServiceImpl");
        return JsonData.buildSuccess(videoService.listVideo());
    }
}