Springboot中的普通类如何调用Service或Dao层的方法

一.新建一个工具类

package com.yyl.newcdss.utils;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * @Author: LongLongA
 * @Description:该工具类是固定写法,用于让其它普通类可以调用Service,Dao层的服务
 * @Date: Created in 16:07 2021/11/17
 */
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;
        }
        System.out.println("---------------------------------------------------------------------");
        System.out.println("========ApplicationContext配置成功,在普通类可以通过调用SpringUtils.getAppContext()获取applicationContext对象,applicationContext="+SpringUtil.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);
    }
}

二.在启动主类中引入这个工具类

package com.yyl.newcdss;

import com.yyl.newcdss.utils.SpringUtil;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Import;


//项目入口
@Import(SpringUtil.class)//让自定义的工具类自动导入
@SpringBootApplication
public class NewcdssApplication {

    public static void main(String[] args) {
        SpringApplication.run(NewcdssApplication.class, args);
    }

}

三。在普通类中调用Service层方法(Dao同理)

//1.获取相关service层的方法
     ApplicationContext applicationContext = SpringUtil.getApplicationContext();
     //这是笔者声明的Service类,使用者可以换成自己定义的
     CandidateService candidateService = applicationContext.getBean(CandidateService.class);

你可能感兴趣的:(SpringBoot,spring,boot)