SpringBoot back door, get a container factory

SpringBoot back door

2020-01-05 (Sunday and cloudy)

In the general category of non-springboot factory management, if you want to get the object factory management, we can no longer use such as injection @Autowired comment at this time of issue SpringBoot official has been given a solution, they provide a "ApplicationContextAware" interfaces, implement this interface, you can get the entire contents of the factory management.

package com.baizhi.cache;

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

//web触发器,作用是获得整个工厂内容,方便非工厂管理的普通类。可以拿到工厂管理的对象(全局容器)
@Component
public class WebWare implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

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

    //通过属性名获取对象的方法
   public static Object getbyName(String name){
       Object bean = applicationContext.getBean(name);
       return bean;
   }

   //通过属性类获取对象的方法
    public static Object getByClass(Class clazz){
        Object bean = applicationContext.getBean(clazz);
        return bean;
    }


}

Published 32 original articles · won praise 1 · views 1180

Guess you like

Origin blog.csdn.net/ASYMUXUE/article/details/103841464