简体   繁体   English

如何使用 Spring Boot AutoWired 和 ScheduledExecutorService?

[英]How to use Spring boot AutoWired and ScheduledExecutorService?

I need to use autowired in more than one class with ScheduledExecutorService, what I have tried is shown in this code.我需要在多个带有 ScheduledExecutorService 的类中使用自动装配,我尝试过的内容显示在此代码中。 logging size of User list in below example always shows 0, even after user added to arraylist.下面示例中用户列表的日志大小始终显示为 0,即使在用户添加到数组列表之后。 How to properly use Autowired and ScheduledExecutorService in spring boot?如何在 Spring Boot 中正确使用 Autowired 和 ScheduledExecutorService?

@Component
public class AnotherClass {
    List<User> users = new ArrayList();

    public void addUser(User user){
        users.add(user);
    }

    public void logUsers(){
        logger.info("User size " + users.size());  <================= Always logs 0, when called from executor
    }

}

@RestController
public class SecondClass {

    @Autowired
    private AnotherClass anotherClass; 

    @GetMapping(value="/user/test")
    public void logUsers(){
        anotherClass.addUser(new User());
    }
}

Application Class应用类

@Component
@SpringBootApplication
public class SpringBootDemoApplication {

    private ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);

    @Autowired
    private AnotherClass anotherClass; 

    @PostConstruct
    public void init() {
        logger();
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringBootDemoApplication.class, args);
    }

    public void logger(){
        exec.scheduleAtFixedRate(new Runnable(){
            @Override
            public void run(){
                try {
                    anotherClass.logUsers();
                }catch (Exception e){
                }
            }
        }, 2000, 1000, TimeUnit.MILLISECONDS);
    }
}

如果您使用Spring @Autowired而不是@AutoWired Annotation,则代码有效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM