springboot调用controller和service层方法
说明
- 最近遇到一个问题,如何在工具类中去访问controller层与service层的方法。
- 因为平时在调用service层时都是在controller中,有配置扫描注入,spring会根据配置自动注入所依赖的服务层。
- 但因我们写的工具类不属于controller层,所以当所写接口需要调用服务层是,常常会为null。
实现
1.创建一个工具类:springutil
package com.ruoyi.web.controller.employment.utils;
import org.springframework.beans.beansexception;
import org.springframework.context.applicationcontext;
import org.springframework.context.applicationcontextaware;
import org.springframework.stereotype.component;
@component
public class springutil implements applicationcontextaware{
private static applicationcontext applicationcontext = null;
@override
public void setapplicationcontext(applicationcontext applicationcontext) throws beansexception {
if(springutil.applicationcontext == null){
springutil.applicationcontext = applicationcontext;
}
}
//获取applicationcontext
public static applicationcontext getapplicationcontext() {
return applicationcontext;
}
//通过name获取 bean.
public static object getbean(string name){
return getapplicationcontext().getbean(name);
}
//通过class获取bean.
public static <t> t getbean(class<t> clazz){
return getapplicationcontext().getbean(clazz);
}
//通过name,以及clazz返回指定的bean
public static <t> t getbean(string name,class<t> clazz){
return getapplicationcontext().getbean(name, clazz);
}
}
2.springboot启动类调用controller和service方法
package com.ruoyi;
import com.ruoyi.web.controller.employment.provportcontroller1;
import com.ruoyi.web.controller.employment.provportcontroller2;
import com.ruoyi.web.controller.employment.utils.springutil;
import org.springframework.boot.springapplication;
import org.springframework.boot.autoconfigure.springbootapplication;
import org.springframework.boot.autoconfigure.jdbc.datasourceautoconfiguration;
import org.springframework.context.applicationcontext;
/**
* 启动程序
*
* @author ruoyi
*/
@springbootapplication(exclude = { datasourceautoconfiguration.class })
public class ruoyiapplication
{
//注入service
private static testservice testservice;
//注入controller
private static testcontroller testcontroller;
public static void main(string[] args) throws interruptedexception {
springapplication.run(ruoyiapplication.class, args);
applicationcontext context = springutil.getapplicationcontext();
testservice= context.getbean(testservice.class);
testcontroller= context.getbean(testcontroller.class);
//调用service方法
testservice.getservice();
//调用controller方法
testcontroller.getcontroller();
}
}
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论