SpringBoot 는 applicationContext 와 getbean 의 두 가지 방식 을 사용 합 니 다.

4825 단어 getBeanspring
첫 번 째:용기 불 러 올 때 설정
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");

두 번 째:응용 프로그램 계승 ContextAware
@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.
     * 

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 functionOperation(ProxyParamDTO params, OperationEntity operationEntity) throws Exception{
        Map 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;
    }

좋은 웹페이지 즐겨찾기