javaweb项目启动后自动查询数据库并刷新数值
一、使用quartz定时器
1、通过反射获取属性,然后刷入数据
public void flashConfigParam(){ //获取要刷新的类 Class<?> clazz = Constants.class;、 //获取数据库的值 List<SysConfig> sysConfigs = getAll(); for (SysConfig sc : sysConfigs) { if(sc == null || StringUtils.isBlank(sc.getName())){ continue; } try { //获取类所对应的类的属性 Field field = clazz.getDeclaredField(sc.getName().trim()); if(field != null){ String type = field.getType().getName(); switch (type) { case "java.lang.Boolean": field.set(clazz, Boolean.valueOf("true".equals(sc.getValue()))); break; case "java.lang.String": field.set(clazz, sc.getValue()); break; case "java.lang.Integer": field.set(clazz, Integer.valueOf(sc.getValue())); break; case "java.lang.Double": field.set(clazz, Double.valueOf(sc.getValue())); break; default: break; } } } catch (Exception e) { logger.error("刷新配置文件SYSCONFIG-->" + sc.getName() + " 异常!", e); } } logger.warn("刷新配置文件SYSCONFIG完成:"+HKDateUtil.formatDateTime(new Date())); }
2、配置spring的定时任务
<bean id="flashSysConfigJobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerFactoryBean"> <property name="jobDetail"> <bean class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean"> <!--指定调用的类 --> <property name="targetObject"> <ref bean="sysConfigService" /> </property> <!--指定调用的方法 --> <property name="targetMethod"> <value>flashConfigParam</value> </property> </bean> </property> <!--启动后运行 --> <property name="startDelay" value="5000"/> <property name="repeatInterval" value="500"/> <property name="repeatCount" value="0"/> <!--间隔5分钟 --> <!--<property name="repeatInterval" value="300000"/>--> </bean>
二、使用PostConstruct注解
Servlet中增加了两个影响Servlet生命周期的注解,@PostConstruct和@PreDestroy 例如:
@PostConstruct public void init() throws IOException{ }
@PostConstruct修饰的方法会在服务器加载Servlet的时候运行,并且只会被服务器执行一次。PostConstruct在构造函数之后执行,init()方法之前执行。PreDestroy()方法在destroy()方法知性之后执行 spring中的执行顺序: @Autowired >> @PostConstruct
上一篇:
IDEA上Java项目控制台中文乱码