工具:Eclipse mars
环境:jdk1.8
说明:这是在学习Spring Task时遇到的一个bug,代码如下:
定时任务类:
package com.task.test; import java.util.Date; import org.springframework.stereotype.Component; @Component public class App { public void execute1(){ System.out.printf("Task: %s, Current time: %s\n", 1, new Date() +" current thread :" +Thread.currentThread().getName()); } public void execute2(){ System.out.printf("Task: %s, Current time: %s\n", 2, new Date() +" current thread :" +Thread.currentThread().getName()); } }
Spring配置文件:
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:task="http://www.springframework.org/schema/task" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.1.xsd"> <!-- 配置注解扫描 --> <context:component-scan base-package="com.task.test"/> <task:scheduler id="taskScheduler" pool-size="100" /> <task:scheduled-tasks scheduler="taskScheduler"> <!-- 即刻开始隔5秒钟触发任务一次 --> <task:scheduled ref="App" method="execute1" cron="0/5 * * * * ?"/> <!-- 即刻开始,隔10秒钟触发任务一次 --> <task:scheduled ref="App" method="execute2" cron="0/10 * * * * ?"/> </task:scheduled-tasks> </beans>
测试代码:
package com.task.test; import java.util.Date; import org.springframework.stereotype.Component; @Component public class App { public void execute1(){ System.out.printf("Task: %s, Current time: %s\n", 1, new Date() +" current thread :" +Thread.currentThread().getName()); } public void execute2(){ System.out.printf("Task: %s, Current time: %s\n", 2, new Date() +" current thread :" +Thread.currentThread().getName()); } }
操作:右键Eclipse编辑区--->点击Run As--->Java Application
报错:
原因:spring配置文件中的 ref 属性值得命名格式应该是驼峰命名法,即将spring配置文件中的ref="App"改为ref="app"即可。
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'App' is defined
时间: 2024-12-20 01:15:44