详解在SpringBoot应用中获取应用上下文方法
程序员文章站
2024-02-28 08:12:16
1、定义上下文工具类:
package com.alimama.config;
import org.springframework.context.app...
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; /** * 任务执行者 * */ 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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。