springboot自定义工具

springboot自定义工具

上下文工具类

你上下文工具类,获取注册的bean。

public class SpringContextUtils implements ApplicationListener<ApplicationPreparedEvent> {

    protected static ApplicationContext context;

    @Override
    public void onApplicationEvent(ApplicationPreparedEvent applicationPreparedEvent) {
        context = applicationPreparedEvent.getApplicationContext();
    }

    public static ApplicationContext getContext() {
        return context;
    }

    public static <T> T getBean(String beanName) {
        return (T) context.getBean(beanName);
    }

    public static <T> T getBean(Class<?> clazz) {
        return (T) context.getBean(clazz);
    }


}



启动类:
@ComponentScan(basePackages = {"com"}, excludeFilters = {@ComponentScan.Filter(type = FilterType.CUSTOM, classes = {CMSFilter.class})})
public class ServiceApplication extends SpringBootServletInitializer {

    private static Logger logger = LoggerFactory.getLogger(ServiceApplication.class);

    @Value("${system.name:unknown}")
    public String currentService;

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
        return builder.listeners(new SpringContextUtils()).sources(ServiceApplication.class);
    }

    public static void main(String[] args) {
        // 配置当前 Main-JAR 的运行路径
        configMainJarRootPath();

        // 判断当前服务是否依赖 springboot 框架
        checkSpringFramework();

        try {
            SpringApplication springApplication = new SpringApplication(ServiceApplication.class);
            springApplication.addListeners(new SpringContextUtils());
            ApplicationContext applicationContext = springApplication.run(args);
            AppContextHelper.setContext(applicationContext, true);
        } catch (Exception e) {
            //启动异常后直接退出 依靠keeper拉起
            logger.error("application start error : " + e.getMessage(), e);
            System.exit(0);
        }
    }

    /**
     * 配置当前 Main-JAR 的运行路径
     */
    private static String configMainJarRootPath() {

        String absolutePath = "";

        // get current main-jar absolute path
        URL jarUrl = ServiceApplication.class.getProtectionDomain().getCodeSource().getLocation();

        logger.info("current main-jar absolute path:" + jarUrl);
        try {
            File file = new File(jarUrl.toURI());

            absolutePath = file.getParentFile().getAbsolutePath();

            // 将当前 main-jar 的 root 目录写入全局业务上下文(缓存)
            BusinessContext.getInstance().setMainJarPath(absolutePath);

        } catch (URISyntaxException e) {
            logger.error("get current main-jar absolute path failed, this will cause some resources load unsuccess");
        }

        return absolutePath;
    }

    /**
     * 检查当前应用的框架,并将结果存入全局对象中(是否基于 springboot)
     */
    private static void checkSpringFramework() {
        boolean result = AnnotationUtils.isAnnotationDeclaredLocally(SpringBootApplication.class, ServiceApplication.class);
        BusinessContext.getInstance().setBaseSpringboot(result);
    }

    public ServiceApplication() {
        FeignHelper.initCurrentService(this.currentService);
    }
}

site:https://blog.csdn.net/wo541075754/article/details/104324070

方式二:

package org.rabbit.consumer.spring;
 
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
 
/**
 * @author hongsir 2017-11-03 19:36
 * @apiNote spring上下文工具类,用于普通类调用springIOC中的对象
 */
@Component
public class SpringContextUtils implements ApplicationContextAware {
	private static ApplicationContext applicationContext = null;
 
	@Override
	public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
		if (SpringContextUtils.applicationContext == null) {
			SpringContextUtils.applicationContext = applicationContext;
		}
	}
 
	/**
	 * @apiNote 获取applicationContext
	 * @author hongsir 2017/11/3 19:40:00
	 */
	public static ApplicationContext getApplicationContext() {
		return applicationContext;
	}
 
	/**
	 * @apiNote 通过name获取 Bean.
	 * @author hongsir 2017/11/3 19:39:00
	 */
	public static Object getBean(String name) {
		return getApplicationContext().getBean(name);
	}
 
	/**
	 * @apiNote 通过class获取Bean.
	 * @author hongsir 2017/11/3 19:39:00
	 */
	public static <T> T getBean(Class<T> clazz) {
		return getApplicationContext().getBean(clazz);
	}
 
	/**
	 * @apiNote 通过name, 以及Clazz返回指定的Bean
	 * @author hongsir 2017/11/3 19:39:00
	 */
	public static <T> T getBean(String name, Class<T> clazz) {
		return getApplicationContext().getBean(name, clazz);
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值