Spring 中普通类/工具类调用 @Service注解的Service层方法

新建一个 ApplicationContextProvider 类:

@Component
public class ApplicationContextProvider implements ApplicationContextAware {
    /**
     * 上下文对象实例
     */
    private static ApplicationContext applicationContext;

    @SuppressWarnings("static-access")
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

    /**
     * 获取applicationContext
     *
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     *
     * @param name
     * @return
     */
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    /**
     * 通过class获取Bean.
     *
     * @param clazz
     * @param 
     * @return
     */
    public static  T getBean(Class clazz) {
        return getApplicationContext().getBean(clazz);
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     *
     * @param name
     * @param clazz
     * @param 
     * @return
     */
    public static  T getBean(String name, Class clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

Service注解时添加name:  “cameraService”

@Service("cameraService")

在普通类中 @Autowired 注入所调用的cameraService

                     调用 ApplicationContextProvider类中的 getBean()方法,传入 Service注解时添加的 name即可调用。

@Component
public class ScheduTask {

    @Autowired
    CameraServiceImpl cameraService ;


    @Scheduled(cron = "0/10 50/1 * * * 2")
    public void testSca(){
        Thread thread = Thread.currentThread();
        String name = thread.getName();
        System.out.println("测试1:"+name);
        System.out.println("定时任务1:"+ new SimpleDateFormat("HH:mm:ss").format(new Date()));
        // get 需要调用的Service的Name
        cameraService = (CameraServiceImpl) ApplicationContextProvider.getBean("cameraService");
        cameraService.deleteCamera("123");
    }

}

 

你可能感兴趣的:(Java)