spring 容器启动执行

问题背景:

容器启动执行后立刻执行改代码 、常用来初始化redis数据、等等

方法一 spring

扫描执行PostConstruct注解方法

spring.xml

1
2

<context:component-scan base-package="com.csdn.uc.init"/>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27


/**
* 容器启动后加载redis
* Created by huoyan403 on 3/22/2017.
*/
@Component
public class AddressToRedisInit{

private static final Logger logger = LoggerFactory.getLogger(AddressToRedisInit.class);
@Autowired
private AreasDao areasDao;
@Autowired
private RedisClient redisClient;

// 启动开关
// @PostConstruct
public void AddressToRedisInit() {

//子线程执行初始化
AddressToRedisThread addressToRedisThread = new AddressToRedisThread();
addressToRedisThread.setRedisClient(redisClient);
addressToRedisThread.setAreasDao(areasDao);
addressToRedisThread.run();

}
}

方法二 springboot

实现 CommandLineRunner 接口

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
 

/**
* description
* 启动后执行 规划每个doc文档存储设置
* @author lishengkai
* @date 2018-03-28 16:47
*/
@Component
public class InitDocIndexSetting implements CommandLineRunner {


@Autowired
ElasticsearchTemplate elasticsearchOperations;

@Autowired
BeanPostProcessor beanPostProcessor;


@Override
public void run(String... args) throws Exception {

Map<String, Object> map = beanPostProcessor.map;

for (Object o : map.values()) {
elasticsearchOperations.createIndexWithSettings(o.getClass());
}

}
}