springboot整合(预加载数据commandlinerunner)

代码包含在此项目中:https://gitee.com/zhangjunqing/spring-boot/tree/master/springboot-sample

1 通过实现commandlinerunner接口,可以在spring加载完进行一些数据的预处理操作。在实现此方法时最好加上@Order注解来指定预加载的顺序。

       添加两个类实现commandlinerunner接口,并指定他们的加载顺序,同时在加载后获取spring 容器中的bean并修改。

 

       1.1  辅助类,放在spring容器当中,可以在预加载程序中注入此类的对象,并且修改其值

package com.springboot.service;

import org.springframework.stereotype.Service;

/**
 * 程序测试辅助类  制定年龄为10
 * @author 76524
 *
 */
@Service
public class ModelTest {
    
    private int age = 10;

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    
}

 

               

       1.2 加载顺序为20的预加载类,并且修改辅助对象的年龄,将其增加1

package com.springboot.commandrunner;

import javax.annotation.Resource;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.springboot.service.ModelTest;

@Component
@Order(20)  //启动时的加载顺序,越小越提前加载
public class StartRunner1 implements CommandLineRunner {
    
    @Resource
    private ModelTest modeTest;
    
    public void run(String... arg0) throws Exception {
        System.out.println("启动预加载1  " + modeTest.getAge());
        modeTest.setAge(modeTest.getAge()+1);   //增加1 
    }

}

 

 

   1.3 加载顺序为40的预加载类,打印新的辅助对象的年龄

package com.springboot.commandrunner;

import javax.annotation.Resource;

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import com.springboot.service.ModelTest;

@Component
@Order(40)  //启动时的加载顺序,越小越提前加载
public class StartRunner2  implements CommandLineRunner{
    
    @Resource
    private ModelTest modeTest;

    public void run(String... arg0) throws Exception {
        System.out.println("启动预加载2 " + modeTest.getAge());
    }

}

 

1.4  结果如下

2017-10-15 15:32:39.205  INFO 17044 --- [           main] s.b.c.e.t.TomcatEmbeddedServletContainer : Tomcat started on port(s): 8080 (http)
启动预加载1  10
启动预加载2 11
2017-10-15 15:32:39.215  INFO 17044 --- [           main] com.springboot.App                       : Started App in 4.901 seconds (JVM running for 5.608)

   

    注意:使用此方法是最好指定加载顺序,并且加载顺序的数值留一些间隔,防止以后再添加预加载类。

转载于:https://www.cnblogs.com/zhangjunqing/p/7674755.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值