发布网友 发布时间:2022-04-22 04:31
共1个回答
热心网友 时间:2023-09-09 22:42
写一个类,实现InitializingBean接口,然后交由spring容器管理
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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
Java代码
public class InitDataListener implements InitializingBean, ServletContextAware{
private UserService userService;//属性。和配置文件对应property name对应
private Logger log = Logger.getLogger(InitDataListener.class);
public UserService getUserService() {
return userService;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
public void afterPropertiesSet() throws Exception {
//在这个方法里面写 初始化的数据也可以。
}
@Override
public void setServletContext(ServletContext arg0) {
//userMap容器存放 userList(用户数据)
List<User> userList = new ArrayList<User>();
try {
userList = userService.queryAllUser();
Map<String, Object> userMap = CachFactory.getInstance().createCach("userMap");
//一个<a href="https://www.baidu.com/s?wd=%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YYm1NbnHbvn1P9mHuWPAfz0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPW6LPWfYnHcsrHb1Pjc4Pj6Y" target="_blank" class="-highlight">工厂模式</a>和<a href="https://www.baidu.com/s?wd=%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YYm1NbnHbvn1P9mHuWPAfz0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPW6LPWfYnHcsrHb1Pjc4Pj6Y" target="_blank" class="-highlight">单例模式</a>的使用。文档最后有代码
for(User user:userList){
userMap.put(user.getUserid(), user);
}
} catch (Exception e) {
log.error("queryAllUser error<a href="https://www.baidu.com/s?wd=%E7%B3%BB%E7%BB%9F%E5%88%9D%E5%A7%8B%E5%8C%96&tn=44039180_cpr&fenlei=mv6quAkxTZn0IZRqIHckPjm4nH00T1YYm1NbnHbvn1P9mHuWPAfz0ZwV5Hcvrjm3rH6sPfKWUMw85HfYnjn4nH6sgvPsT6KdThsqpZwYTjCEQLGCpyw9Uz4Bmy-bIi4WUvYETgN-TLwGUv3EPW6LPWfYnHcsrHb1Pjc4Pj6Y" target="_blank" class="-highlight">系统初始化</a>查询所有用户出错");
}
System.out.println(userList.size());
}
Java代码
<!-- spring系统启动以后,加载该类,查询所有数据 -->
<bean class="adtec.init.InitDataListener">
<property name="userService" ref="userService"></property>
</bean>