SpringBoot 使用ApplicationContext 及 getbean的兩種方式

劍靈尊發表於2019-10-24

第一種:容器載入時設定

public class ProxyApplication {
	public static void main(String[] args) {
		ApplicationContext applicationContext = SpringApplication.run(ProxyApplication.class, args);
		SpringContextUtil.setApplicationContext(applicationContext);
	}
}

例項化SpringContextUtil

public class SpringContextUtil {

    // Spring應用上下文環境
    private static ApplicationContext applicationContext;

    /**
     * 實現ApplicationContextAware介面的回撥方法,設定上下文環境
     */
    public static void setApplicationContext(ApplicationContext applicationContext)throws BeansException  {
        SpringContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     *  根據beanId返回Spring中的例項
     * @Date 2019-08-07 17:36
     * @param
     * @return
     **/
    public static Object getBean(String beanId) throws BeansException {
        return applicationContext.getBean(beanId);
    }
}

使用場景:實體中初始化資訊,載入類資訊到容器中

@Data
@Configuration
public class AutoLogonConfig {
	private boolean autoLogon = false;
	
	private String loginName = "";
	
	private String password = "";

	private String ip = "";
	
	public AutoLogonConfig(@Value("${loginFilePath}") String  loginFilePath){
		Yaml yaml = new Yaml();
		InputStream in;
		try {
			File file = new File(loginFilePath);
			in = new FileInputStream(file);
			Map map = (Map) yaml.load(in);
			Pub.loginFilePath = loginFilePath;
			this.autoLogon=(boolean) map.get("autoLogon");
			this.loginName=(String) map.get("loginName");
			this.password=(String) map.get("password");
			this.ip=(String) map.get("ip");
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
AutoLogonConfig autoLogonConfig = (AutoLogonConfig) SpringContextUtil.getBean("autoLogonConfig");

第二種:繼承ApplicationContextAware

@Component
public class ApplicationContextUtil implements ApplicationContextAware {

    /**
     * 獲取bean
     * @param name
     * @return
     * @throws BeansException
     */
    public static Object getBean(String name) throws BeansException {
        Object o = applicationContext.getBean(name);
        return o;
    }
    private static ApplicationContext applicationContext;

    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},
     * {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware}, if applicable.
     *
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        ApplicationContextUtil.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext(){
        return applicationContext;
    }


}

使用場景:需要通過反射機制

public Map<String,String> functionOperation(ProxyParamDTO params, OperationEntity operationEntity) throws Exception{
        Map<String,String> m = null;
        String className;
        String functionName;
        // [0]:ClassName, [1];functionName
        String[] arr = getFunctionName(operationEntity);
        className = arr[0];
        functionName = arr[1];
        operationEntity.setParamDto(params);
        try {
            // getBean
            Object o = ApplicationContextUtil.getBean(className);
            // getClass
            Class<?> clazz = o.getClass();
            // getMethod by class
            Method method = clazz.getMethod(functionName, OperationEntity.class);
            // execute method and get returned value
            m = (HashMap) method.invoke(o, operationEntity);
            System.out.println(operationEntity.getOperationOrder() + " : " + method.getName());
        } catch (NoSuchMethodException | BeansException e) {
            otherFunctions(operationEntity, arr);
        } catch (IllegalAccessException | InvocationTargetException e) {
            e.printStackTrace();
            throw e;
        }
        return m;
    }

 

相關文章