SpringBoot project starts to execute tasks and obtains Service through reflection

1. Several ways to start and execute tasks in SpringBoot project

 

After sorting out, the following common methods are obtained for your reference.

1. Use filters

init(): This method is called when the tomcat container starts to initialize the filter, and it will only be called once in the entire life cycle of the Filter. You can add what you want to execute in this method.

@Component
public class MyFilter implements Filter {
 
    /**
     * init() :该方法在tomcat容器启动初始化过滤器时被调用,它在 Filter 的整个生命周期只会被调用一次。
     * doFilter() :容器中的每一次请求都会调用该方法, FilterChain(放行) 用来调用下一个过滤器 Filter。
     * destroy(): 当容器销毁过滤器实例时调用该方法,在方法中销毁或关闭资源,在过滤器 Filter 的整个生命周期也只会被调用一次。
     */
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        System.out.println("Filter 前置");
    }
 
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        System.out.println("Filter 处理中");
        filterChain.doFilter(servletRequest, servletResponse);
    }
 
    @Override
    public void destroy() {
        System.out.println("Filter 后置");
    }
}

2. Implement the InitializingBean interface, the code is as follows:

@Component
public class SpringContext implements InitializingBean {
 
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println(" ======================implements InitializingBean 方法开始执行==================");
    }
}


3. Implement the ApplicationListener interface, the code is as follows:

@Component
public class SpringContext implements ApplicationListener<ApplicationStartedEvent> {
    @Override
    public void onApplicationEvent(ApplicationStartedEvent event) {
        System.out.println(" ======================implements ApplicationListener方法开始执行==================");
    }
}


4. Implement the ApplicationRunner interface, the code is as follows:

@Component
public class SpringContext implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) throws Exception {
        System.out.println(" ======================implements ApplicationRunner==================");
    }
}


5. Implement the CommandLineRunner interface, the code is as follows:

@Component
public class SpringContext implements CommandLineRunner {
    @Override
    public void run(String... args) throws Exception {
        System.out.println(" ======================implements CommandLineRunner==================");
    }
}


6. Use @PostConstruct annotation, the code is as follows:

@Component
public class SpringContext {
    @PostConstruct
    public void run() {
        System.out.println(" ======================@PostConstruc方法开始执行==================");
    }
}

2. SpringBoot obtains Service through reflection

 

scenes to be used


Call the method in the BUtil tool class in AService. The method in the BUtil tool class needs to query the database operation at this time. The query database operation needs to use the select() interface in BService. At this time, we cannot succeed in using @Autowird BService bService in BUtil injected.

Solution


Obtain objects from the container by implementing the ApplicationContextAware interface

reflection tools

package com.mes.material.utils;


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


@Component
public class SpringBeanUtils implements ApplicationContextAware {

    private static ApplicationContext context;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        context = applicationContext;
    }

    public static <T> T getBean(Class<T> requiredType) {

        if (context == null) {
            throw new IllegalStateException("spring 环境没有启动!");
        }
        return context.getBean(requiredType);
    }

    public static <T> T getBean(String beanName, Class<T> requiredType) {

        if (context == null) {
            throw new IllegalStateException("spring 环境没有启动!");
        }
        return context.getBean(beanName, requiredType);

    }

    public static ApplicationContext getContext() {


        if (context == null) {
            throw new IllegalStateException("spring 环境没有启动!");
        }
        return context;
    }
}

Instructions

package com.mes.material;

import com.mes.material.domain.vo.MaterialStatisticsVo;
import com.mes.material.quartz.service.impl.IMaterialEanConfigImpl;
import com.mes.material.service.impl.IMaterialStatisticsServicesImpl;
import com.mes.material.service.impl.IMaterialInventoryPlanServiceImpl;
import com.mes.material.utils.SpringBeanUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
 * @author best_liu
 * @version 1.0
 * @date 2021/9/29
 */
@Component
@Order(value = 1)
@Slf4j
public class MaterialStatisticsStartUp implements ApplicationRunner {

    private IMaterialStatisticsServicesImpl materialStatisticsServicesImpl;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        try {
            materialStatisticsServicesImpl = SpringBeanUtils.getBean("IMaterialStatisticsServicesImpl", IMaterialStatisticsServicesImpl.class);
            MaterialStatisticsVo materialStatisticsVo = new MaterialStatisticsVo();
            materialStatisticsServicesImpl.materialStatistics(materialStatisticsVo);
        } catch (Exception e) {
            log.error("线程错误!", e);
        }
    }
}

Guess you like

Origin blog.csdn.net/askuld/article/details/130967302