SpringBoot 获取应上下文 ApplicationContent

发布于 2024-04-24 07:05:16 字数 2681 浏览 25 评论 0

1、定义上下文工具类

package com.alimama.config;

import org.springframework.context.ApplicationContext;
/**
 * 上下文获取工具类
 * @author mengfeiyang
 *
 */
public class SpringContextUtil {
	  private static ApplicationContext applicationContext;

	  public static void setApplicationContext(ApplicationContext context) {
	    applicationContext = context;
	  }
	  
	   public static Object getBean(String beanId) {
	    return applicationContext.getBean(beanId);
	  }
}

2、在启动入口类中注入 applicationContext

package com.alimama;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.embedded.ConfigurableEmbeddedServletContainer;
import org.springframework.boot.context.embedded.EmbeddedServletContainerCustomizer;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.ComponentScan;

import com.alimama.config.SbootConfig;
import com.alimama.config.SpringContextUtil;
import com.alimama.config.ZKConfig;
import com.alimama.quartz.InitTask;

/**
 * spring boot 启动入口类
 * @author mengfeiyang
 *
 */
@ComponentScan
@SpringBootApplication
@EnableConfigurationProperties({ZKConfig.class,SbootConfig.class})
public class SbootApplication implements EmbeddedServletContainerCustomizer{

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

	@Override
	public void customize(ConfigurableEmbeddedServletContainer container) {
		
	}
}

3、调用方法

package com.alimama.quartz;

import java.io.IOException;

import org.phoenix.api.action.IInterfaceAPI;
import org.phoenix.api.action.InterfaceAPI;
import org.quartz.Job;
import org.springframework.beans.factory.annotation.Autowired;

import com.alimama.config.SpringContextUtil;
import com.alimama.dto.TaskBean;
import com.alimama.service.IConfigService;
import com.alimama.service.impl.ConfigService;
/**
 * 任务执行者
 * @author mengfeiyang
 *
 */
public class TaskHandler implements Job{
	private ConfigService configService = (ConfigService) SpringContextUtil.getBean("configService");
	private IInterfaceAPI interf = new InterfaceAPI();
	@Override
	public void execute(JobExecutionContext arg0){
		String watchDogServer = configService.getwatchDogServer();
	    System.out.println(watchDogServer);
	}
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

鸢与

暂无简介

文章
评论
26 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文