Spring手动获取bean的四种方式

一、实现BeanFactoryPostProcessor接口

@Component
public class SpringUtil implements BeanFactoryPostProcessor {

    private static ConfigurableListableBeanFactory beanFactory;

    public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
        this.beanFactory = beanFactory;
    }

    /**
     * 通过name获取 Bean对象
     * @param name
     * @return Object 一个以所给名字注册的bean实例
     */
    public static  <T> T getBean(String name) {
        return (T) beanFactory.getBean(name);
    }

    /**
     * 通过class获取Bean对象
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        return beanFactory.getBean(clazz);
    }

    /**
     * 如果BeanFactory包含一个与所给名称匹配的bean对象,则返回true
     * @param name
     * @return
     */
    public static boolean containsBean(String name){
        return beanFactory.containsBean(name);
    }

    /**
     * 判断bean对象是一个singleton还是一个prototype
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     */
    public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException{
        return beanFactory.isSingleton(name);
    }

    /**
     * 通过 name获取 bean 的类型
     * @param name
     * @return
     * @throws NoSuchBeanDefinitionException
     */
    public static Class<?> getType(String name) throws NoSuchBeanDefinitionException{
        return beanFactory.getType(name);
    }

    /**
     * 通过 name 获取 bean定义的别名
     * @param name
     * @return
     */
    public static String[] getAliases(String name){
        return beanFactory.getAliases(name);
    }
}

二、实现ApplicationContextAware接口

@Component
public class BeanUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        BeanUtil.applicationContext = applicationContext;
    }
    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }
    /**
     * 通过name获取 Bean对象
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean对象
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name和Class返回指定的Bean对象
     *
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

    /**
     * 获取当前的环境配置
     * @return
     */
    public static String[] getActiveProfiles(){
        return getApplicationContext().getEnvironment().getActiveProfiles();
    }
}

三、注解 @PostConstruct 初始化时获取

@Component
public class BeanStatic {

    @Autowired
    private TestService testService;

    @Autowired
    private static TestService staticTestService;

    /**
     * 用于在依赖关系注入完成之后需要执行的方法上
     * 执行任何初始化操作
     */
    @PostConstruct
    public void init() {
        // 初始化时把testService对象赋值给当前类定义的静态变量
        staticTestService = testService;
    }

    // 在当前类调用业务接口
    public static String getTest() {
        return staticTestService.test();
    }
}

四、通过启动类ApplicationContext获取

@SpringBootApplication
public class WebApplication {

    public static ConfigurableApplicationContext applicationContext;

    public static void main(String[] args) {
        System.out.println("正在启动。。。");
        applicationContext = SpringApplication.run(WebApplication.class, args);
        System.out.println("启动成功");
    }
}

调用方式

@RestController
@RequestMapping("/bean")
@Api(tags = "手动获取Bean对象测试")
public class BeanController {

    @GetMapping("test1")
    @ApiOperation("方式一")
    @ApiOperationSupport(order = 1)
    public IResult test1()
    {
        TestService testService = SpringUtil.getBean(TestService.class);
        String result = testService.test();
        return IResult.success(result);
    }

    @GetMapping("test2")
    @ApiOperation("方式二")
    @ApiOperationSupport(order = 2)
    public IResult test2()
    {
        TestService testService = BeanUtil.getBean(TestService.class);
        String result = testService.test();
        return IResult.success(result);
    }

    @GetMapping("test3")
    @ApiOperation("方式三")
    @ApiOperationSupport(order = 3)
    public IResult test3()
    {
        String result = BeanStatic.getTest();
        return IResult.success(result);
    }

    @GetMapping("test4")
    @ApiOperation("方式四")
    @ApiOperationSupport(order = 4)
    public IResult test4()
    {
        TestService testService = WebApplication.applicationContext.getBean(TestService.class);
        String result = testService.test();
        return IResult.success(result);
    }
}
posted @ 2022-09-22 10:56  盗梦笔记  阅读(2193)  评论(0编辑  收藏  举报