请帮助我,这种情况。 Hibernate + Google Guice框架。 添加了一个调度程序,设置每10秒钟执行一次(用于测试)以调用searchFile()方法,在该方法中检查文件夹中的文件,如果文件夹不为空,则调用解析器和解析文件并使用服务-dao-写入数据库。 (PostgreSQL)
启动应用程序时,不会调用调度程序。
我的课程如下:接口 SchedulerTask :
import com.google.inject.ImplementedBy;
@ImplementedBy(SchedulerTaskBean.class)
public interface SchedulerTask {
void startSchedulerTask();
void searchFile();
}
其实现(SchedulerTaskBean):
import com.google.inject.Inject;
import com.google.inject.Singleton;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import java.io.File;
import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
@Singleton
public class SchedulerTaskBean implements Job, SchedulerTask {
private static final Logger LOGGER = LogManager.getLogger(SchedulerTaskBean.class);
@Inject
private SchedulerTask schedulerTask;
@Inject
private CsvService csvService;
@Override
public void startSchedulerTask() {
ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleWithFixedDelay(this::searchFile, 0, 10, TimeUnit.SECONDS);
// executor.scheduleAtFixedRate(folder::searchFile, 0, 10, TimeUnit.SECONDS);
searchFile();
}
public SchedulerTaskBean() {
startSchedulerTask();
}
@Override
public void searchFile() {
Parser parser = new CsvParserFromLib();
File dir = new File("/home/prog5/Documents/test/");
// если объект представляет каталог
if (dir.isDirectory()) {
File[] listFiles= dir.listFiles();
// Если папка не пустая - парсим что там есть, и переносим спаршеный файл в другую папку, чтоб второй раз его не спарсить.
if(listFiles != null && listFiles.length>0){
for (File file : listFiles) {
List<CsvStructureEntity> listStructure = parser.parse(file);
if (listStructure != null) {
try {
csvService.create(listStructure);
} catch (DataNotFoundException e) {
LOGGER.error(e);
}
} else {
// todo переместить файл в папку "error"
File badFolder = new File("/home/prog5/Documents/test/error");
dir.renameTo(badFolder);
}
}
}
}
}
@Override
public void execute(JobExecutionContext context) throws JobExecutionException {
searchFile();
}
}
但是如果你移动
@Inject
private SchedulerTask schedulerTask;
在另一个控制器(例如授权控制器)中运行该应用程序,它启动并进入我的searchFile()方法(到断点),并且我的服务不为null,它工作正常。
请帮助我如何强制Google Guice在应用程序启动时初始化我的计划程序,而不是将其转移到其他控制器?为了使它在应用程序启动时自动运行,例如每12个小时(现在显示为10秒钟用于测试),我的方法是否正确?
这是我的 CsvService:
@ImplementedBy(CsvServiceBean.class)
public interface CsvService {
List<CsvStructureEntity> create(List<CsvStructureEntity> csvStructureEntity) throws DataNotFoundException;
}
CsvServiceBean:
public class CsvServiceBean implements CsvService {
private static final Logger LOGGER = LogManager.getLogger(CsvServiceBean.class);
@Inject
private CsvDao csvDao;
@Transactional
@Override
public List<CsvStructureEntity> create(final List<CsvStructureEntity> csvStructureEntity) {
csvDao.persistAll(csvStructureEntity);
return csvStructureEntity;
}
}
CsvDao:
@ImplementedBy(CsvDaoBean.class)
public interface CsvDao {
void persistAll(List<CsvStructureEntity> csvStructureEntity);
}
CsvDaoBean:
public class CsvDaoBean extends ValidatableDaoBean<CsvStructureEntity, Long> implements CsvDao {
private static final Logger LOGGER = LogManager.getLogger(CsvDaoBean.class);
@Override
protected Class<CsvStructureEntity> getEntityClass() {
return CsvStructureEntity.class;
}
}
ValidatableDaoBean:
public abstract class ValidatableDaoBean<Entity, Id> extends AbstractJpaDao<Entity, Id> {
@Override
public void persist(final Entity entity) {
validate(entity);
super.persist(entity);
}
@Override
public Entity merge(final Entity entity) {
validate(entity);
return super.merge(entity);
}
private void validate(Entity entity) {
if(entity == null) {
throw new ValidationException("Object is null.");
}
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Entity>> violations = validator.validate(entity);
if(violations.size() > 0) {
List<String> messages = new ArrayList<>();
for (ConstraintViolation<Entity> violation : violations) {
messages.add(violation.getMessage());
}
throw new ValidationException(StringUtils.join(messages, ", "));
}
}
@Override
public void persistAll(List<Entity> entities) {
super.persistAll(entities);
}
}
非常感谢!