• Springboot项目启动时加载数据库数据到内存


    Springboot项目启动时加载数据库数据到内存

    1、使用@PostConstruct注解

    @Component
    public class CodeCache {
        public static Map<String, String> codeMap = new HashMap<String, String>();
        
        @Autowired
        private ICodeService codeService;
        
        @PostConstruct
        public void init(){
            System.out.println("系统启动中。。。加载codeMap");
            List<Code> codeList = codeService.selectAll();
            for (Code code : codeList) {
                codeMap.put(code.getKey(), code.getValue());
            }
        }
        
        @PreDestroy
        public void destroy(){
            System.out.println("系统运行结束");
        }
    }

    注意:@PostConstruct优先级在@Autowired @Value之后,所以可以获取相关的值

    2、CommandLineRunner

      在项目中经常需要进行初始化一些数据(比如缓存等),以便后面调用使用。spring boot可以通过CommandLineRunner接口实现启动加载功能。 

    @Component
    @Order(1) //初始化加载优先级 数字越小优先级越高
    public class Init implements CommandLineRunner {
    
        @Resource
        private IESignInitService eSignInitService;
    
        @Override
        public void run(String... args) throws Exception {
            eSignInitService.init();
        }

    注意:CommandLineRunner 加载会在项目启动完成之后进行加载

    3、二者区别

    @PostConstruct 要比实现CommandLineRunner的类加载的要早;CommandLineRunner 是在项目启动完之后加载;

    如果用@PostConstruct 使用这个service可能会空指针异常, 以为@PostConstruct修饰的方法加载的早, 用到的那个service此时还未加载到spring容器中;

    创建bean的时候执行顺序:Constructor(构造方法) -> @Autowired(依赖注入) -> @PostConstruct(注释的方法)。

    在springboot完全初始化完毕后,会执行CommandLineRunner和ApplicationRunner,两者唯一的区别是参数不同,但是不会影响,都可以获取到执行参数。CommandLineRunner对于参数格式没有任何限制,ApplicationRunner接口参数格式必须是:–key=value;

    注:使用注解@PostConstruct是最常见的一种方式,存在的问题是如果执行的方法耗时过长,会导致项目在方法执行期间无法提供服务。

  • 相关阅读:
    上架的问题
    moya rxswift的简单实用
    MySql的简单使用,所有的代码基于MAC
    H5测试区别与PC端测试关注点
    测试小结
    测试之找回密码
    转Web安全测试之XSS
    一个最简单的登录页面测试case
    web测试特别点
    关于web测试
  • 原文地址:https://www.cnblogs.com/lizm166/p/16542021.html
Copyright © 2020-2023  润新知