首页 > 解决方案 > @EnableScheduling 似乎不适用于 Java 1.7 代码

问题描述

我正在使用 Java 1.7 和 Spring 4.3.4.RELEASE

在以下位置有一个属性文件:

/opt/myapp.properties

这仅包含以下条目:

name = true

Java 代码

@EnableScheduling
@Controller
public class PropertiesUtil {

    @Scheduled(fixedDelay = 10000) 
    public String getPropertyValue() throws IOException {
        Properties properties = new Properties();
        InputStreamReader in = null;
        String value = null;
        try {
             in = new InputStreamReader(new FileInputStream("/opt/myapp/app.properties"), "UTF-8");
             properties.load(in);
             value =  properties.getProperty("name");
             logger.info("\n\n\t\tName: " + value + "\n\n");
        } 
        finally {
            if (null != in) {
                try {
                    in.close();
                } 
                catch (IOException ex) {}
            }
        }
        return value;
    }
}

我的休息端点:

@RestController
public class PropertyController {
    @RequestMapping(value="/checkProperty", method = RequestMethod.GET, produces = "application/json")
    public ResponseEntity<Object> checkProperty() throws IOException {
        PropertiesUtil propertiesUtil = new PropertiesUtil();
        String value = propertiesUtil.getPropertyValue();
        return new ResponseEntity<Object>("Check for Property", headers, HttpStatus.OK);
    }
}

当我构建这个 mvn clean install 并将它部署为一个war文件时,我必须明确地点击我的休息端点才能让它工作(查看我的日志文件中的“name = true”)......

我试图让 Spring Web App使用和注释/opt/myapp/app.properties每 10 秒检查一次文件。@EnableScheduling@Scheduled(fixedDelay = 10000)

现在,我必须手动点击我的 Rest Endpoint 才能查看该属性的值。

标签: javaspring

解决方案


通过创建一个 Spring Config 文件让它工作:

@Configuration
@EnableScheduling
public class PropertiesUtilConfig {

    @Bean
    public PropertiesUtil task() {
        return new PropertiesUtil();
    }

}

PropertiesUtil 不需要@EnableScheduling 注解,只需要@Controller:

@Controller
public class PropertiesUtil {

    @Scheduled(fixedDelay = 10000) 
    public String getPropertyValue() throws IOException { 
        // inline code
    }
}

推荐阅读