我仍然是spring boot的初学者,我使用spring JPA从同一数据库中的多个表中获取数据,并且一切正常,我曾经在Main
上运行我的应用程序,但在这里我添加了一个Controller
类并在那里运行东西,然后我使用@Scheduled(fixedRate=7000)
而不是创建无限循环来保持db中的数据并保持活动,该应用程序运行良好,但在运行时,该应用程序执行了两次而不是在计划开始之前,有一次关于这里发生的事情有任何想法:
Mainclass:
@SpringBootApplication
@EnableScheduling
public class AccessingDataJpaApplication {
public static void main(String[] args) throws Exception{
SpringApplication.run(AccessingDataJpaApplication.class);
}
}
Controller
类:
@Controller
@EnableScheduling
public class MainController {
private static final Logger logger = LoggerFactory.getLogger(MainController.class);
@Autowired
private CustomerRepository customerRepository;
@Autowired
private MessageRepository messageRepository;
private Set<String> camps = new HashSet<String>();
@Bean
@Scheduled(fixedRate=7000)
public void run(){
logger.info("Running");
if((customerRepository.findAllByStatusAndCampType(0, 1).size()) > 0 ){
for(Customer customer : customerRepository.findAll()){
System.out.println(customer.getCampCd());
camps.add(customer.getCampCd());
}
System.out.println("----------------------------------------");
for(MessageCampain messagecampain : messageRepository.findAllByCampCdIn(camps)) {
System.out.println(messagecampain.toString());
}
System.out.println("------------------------------------------");
for(String value : camps) {
System.out.println(value);
}
}
}
}
执行日志:
[ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect
[ main] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
[ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
[ main] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
[ main] c.e.accessingdatajpa.MainController : Running
[ main] o.s.s.c.ThreadPoolTaskScheduler : Initializing ExecutorService 'taskScheduler'
[ main] c.e.a.AccessingDataJpaApplication : Started AccessingDataJpaApplication in 5.467 seconds (JVM running for 6.242)
[ scheduling-1] c.e.accessingdatajpa.MainController : Running
[ scheduling-1] c.e.accessingdatajpa.MainController : Running
您会注意到Running
字
这是因为您将run()
中的MainController
注释为@Bean
,这将创建一个名为lite
的lite
模式bean。 (Spring内部将此bean表示为run
的类型)