如何在系统启动时能够调用spring的注解@Service方法

系统中有一个TimerTask,需要在系统启动时就执行,而该TimerTask中要用到一些Service(Service中还用到了Dao),系统是采用spring的注解的,如@Controller @Service @Repository等。

在web.xml中配置

<servlet>
<servlet-name>smcInitServlet</servlet-name>
<servlet-class>com.xxx.common.util.InitServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>


TimerTask就在此InitServlet中被创建执行的

MmsResendTimer mmsResend = new MmsResendTimer();
Timer mmsResendTimer = new Timer();
mmsResendTimer.schedule(mmsResend, 0, 1000 * 60 * 60);


结果是在启动系统时会报一个错
Exception in thread "Timer-0" java.lang.NullPointerException


原因是在该TimerTask中引用到了

@Autowired
@Qualifier("MMSTableService")
private MMSTableService mmsTableService;


而该Service在代码执行的时候是null

解决办法1:
在spring配置文件中显式的定义一个bean
<bean class="com.xxx.MMSTableServiceImpl">


然后在TimerTask引用的时候换一种定义Service的方式:

MMSTableServiceImpl mmsTableService = (MMSTableServiceImpl)ClassPathXmlApplicationContext.getBean(MMSTableServiceImpl.class);



解决办法2:
在InitServlet中删除创建TimerTask的代码,然后直接在spring配置文件中增加以下代码:


<bean class="com.xxx.protocolstack.mms.timer.MmsResendTimer" init-method="run"></bean>


在这里推荐使用第二种方式,比较简洁方便

不过要注意了,MmsResendTimer类里面一定要有默认的自构造方法
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值