定时任务
@Component
public class AlarmTask implements ServletContextListener{
private Timer timer;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
if(timer!=null) timer.cancel();
}
@Override
public void contextInitialized(ServletContextEvent arg0) {
timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
work();
}
}, 5*1000, 30*1000);// 5秒后执行,间隔30秒执行一次。
}
private void work() {
//定时执行的操作
System.out.println("扫描开始....");
this.getAlarmPoint();
}
public void getAlarmPoint(){
//执行的业务代码
}
}
srping在普通类中注入依赖
//方法一:基于注解
@Component //申明为spring组件
public class TestUtils {
@Autowired
private TestService testService; //添加所需service的私有成员
private static TestUtils testUtils ; // 关键点1 静态初使化 一个工具类 这样是为了在spring初使化之前
public void setTestService(TestService testService) {
this.testService = testService;
}
@PostConstruct //关键二 通过@PostConstruct 和 @PreDestroy 方法 实现初始化和销毁bean之前进行的操作
public void init() {
testUtils = this;
testUtils.testService = this.testService; // 初使化时将已静态化的testService实例化
}
这样下面的代码中就可以通过 testUtils.testService 来调用service处理
//方法二
获取WebApplicatContext ,然后在这个对象中去获取beans
1、写一个工具类SpringTool:
package com.zhiyu.util;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
/**
* 通过该类即可在普通工具类里获取spring管理的bean
* @author wolf
*
*/
public final class SpringTool implements ApplicationContextAware {
private static ApplicationContext applicationContext = null;
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
if (SpringTool.applicationContext == null) {
SpringTool.applicationContext = applicationContext;
System.out.println(
"========ApplicationContext配置成功,在普通类可以通过调用ToolSpring.getAppContext()获取applicationContext对象,applicationContext="
+ applicationContext + "========");
}
}
public static ApplicationContext getApplicationContext() {
return applicationContext;
}
public static Object getBean(String name) {
return getApplicationContext().getBean(name);
}
}
2、在applicationContext.xml里面去注入bean:
<bean class="com.zhiyu.util.SpringTool"/>
3、在普通的类里面加入这行代码.就成功的注入了service层:
第一种情况 适用于Service起了别名 @Service(“”UserService” “)标注了bean的名字
ApplicationContext appCtx = SpringContextUtil.getApplicationContext();
UserService bean = (UserService)SpringContextUtil.getBean("UserService");
第二种情况 适用于 @Service
ApplicationContext appCtx = SpringContextUtil.getApplicationContext();
UserService bean = (UserService)SpringContextUtil.getBean(UserService.class);
取出list中时间最近的一次数据
public PointData getNewData(List<PointData> datas){
PointData pointData = new PointData();
Long dates[] = new Long[datas.size()];
for (int i = 0; i < datas.size(); i++) {
dates[i] = datas.get(i).getDate().getTime();
}
Long maxDate = dates[0];
pointData = datas.get(0);
for (int i = 0; i < dates.length; i++) {
if (dates[i] > maxDate) {
maxDate = dates[i];
pointData = datas.get(i);
}
}
return pointData;
}