Encountered invalid #Scheduled method 'methodName': Only no-arg methods may be annotated with #Scheduled - spring

plz I don't know wath is the exact problem in the code if I add Scheduled annotatiçon in my code suddenly this error appears
if you have any soulustion please.
plz I don't know wath is the exact problem in the code if I add Scheduled annotatiçon in my code suddenly this error appears
if you have any soulustion please.
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
12-09-2019 18:11:54.908 [restartedMain] ERROR o.s.boot.SpringApplication.reportFailure - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'missionResource': Unsatisfied dependency expressed through field 'missionManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'missionImpl' defined in file [C:\Users\El Oussa\Desktop\vgas-api\vgas-manager\target\classes\ma\valueit\vgas\manager\business\impl\MissionImpl.class]: Initialization of bean failed; nested exception is java.lang.IllegalStateException: Encountered invalid #Scheduled method 'editMission': Only no-arg methods may be annotated with #Scheduled
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
I have added #EnableScheduling in SpringBootApplication
--------------------------------------------------------
#SpringBootApplication
#EnableScheduling
#ComponentScan("com.qaiboub.vs")
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
#Service
public class MissionImpl extends CrudManagerImpl<MissionDto, Integer, MissionEntity, MissionService, MissionConverter> implements MissionManager {
#Autowired
private MissionService missionService;
#Autowired
private MissionConverter missionConverter;
enter code here
#Override
public MissionService getService() {
return missionService;
}
#Override
public MissionConverter getConverter() {
return missionConverter;
}
#Scheduled(cron = "0 15 18 * * *")
public void editMission(Integer id, MissionDto missionDto) {
if (StringUtils.isEmpty(id)) {
throw new MissingIdException();
}
if (missionDto == null) {
throw new InvalidPayloadException();
}
if (!id.equals(missionDto.getId())) {
throw new BusinessException(CommonErrorCode.TRYING_TO_EDIT_ANOTHER_ENTITY);
}
missionEntity = missionConverter.convertFrom(missionDto);
missionEntity = missionService.save(missionEntity);
}
}

remove the function arg. Scheduler don't take arg in their functions

You need to remove all the arguments from the function, the scheduler does not accept any argument
public void syncData(#RequestParam(name = "created_at_from") String createdAtFrom,
#RequestParam(name = "created_at_to") String createdAtTo) {}
Correct format is
public void syncData() throws Exception {}
Use this link for additional details:
https://www.baeldung.com/shedlock-spring

Related

No qualifying bean of type 'org.springframework.batch.core.Step' available

Error:
2020-04-24 00:52:50,892 INFO bcm.BankruptcyCasePurgeDownloadJobProcessingApplication - No active profile set, falling back to default profiles: default
2020-04-24 00:52:53,038 WARN annotation.AnnotationConfigApplicationContext - Exception encountered during context initialization - cancelling refresh attempt: org.spri
ngframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bankruptcyCasePurgeDownloadJob' defined in class path resource [com/cgi/ec/down
load/bcm/BankruptcyCasePurgeDownloadSetupConfiguration.class]: Unsatisfied dependency expressed through method 'bankruptcyCasePurgeDownloadJob' parameter 1; nested exce
ption is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'org.springframework.batch.core.Step' available: expected at least
1 bean which qualifies as autowire candidate. Dependency annotations: {}
2020-04-24 00:52:53,071 INFO logging.ConditionEvaluationReportLoggingListener -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
//Java code
#SpringBootApplication
#ComponentScan(basePackages = {"com.cgi.ec.download.bcm", "com.cgi.ec.interfaces.util.properties"})
public class BankruptcyCasePurgeDownloadJobProcessingApplication {
private static final XLogger LOG = XLoggerFactory.getXLogger(BankruptcyCasePurgeDownloadJobProcessingApplication.class);
public static void main(String[] args) throws Exception {
String arguments = Arrays.toString(args);
LOG.debug("[main] starting with args: {}", arguments);
ConfigurableApplicationContext ctx = SpringApplication.run(BankruptcyCasePurgeDownloadJobProcessingApplication.class, args);
JobLauncher jobLauncher = ctx.getBean(JobLauncher.class);
System.out.println("Spring boot success");
Job jobInstance = ctx.getBean("bankruptcyCasePurgeDownloadJob", Job.class);
jobLauncher.run(jobInstance, InterfacesCommonConfiguration.getJobParameters());
}
}
#Configuration
#EnableBatchProcessing
public class BankruptcyCasePurgeDownloadSetupConfiguration {
private static final XLogger LOG = XLoggerFactory.getXLogger(BankruptcyCasePurgeDownloadSetupConfiguration.class);
private static final String JOB_NAME = "bankruptcyCasePurgeDownload";
/**
* Main SpringBatch Job that defines the steps to the batch job
*
* #return SpringBatch Job object
*/
#Bean
public Job testStepJob(JobBuilderFactory jobBuilderFactory, Step bankruptcyCasePurgeDownloadStep) {
LOG.entry();
return LOG.exit(jobBuilderFactory.get(JOB_NAME + "Job")
.incrementer(new RunIdIncrementer())
.flow(testStep)
.end()
.build());
}
You are trying to inject a bean of type Step here:
#Bean
public Job testStepJob(JobBuilderFactory jobBuilderFactory, Step bankruptcyCasePurgeDownloadStep) {
...
}
but according to the error, your application context does not contain a bean of that type.
Make sure you import a configuration class containing your step bean definition or define a bean of that type in your scanned packages.

Bean instantiation via factory method failed

I am getting below error:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStorageServiceBean' defined in com.primesolutions.fileupload.settings.FileStorageProperties: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.primesolutions.fileupload.service.FileStorageService]: Factory method 'fileStorageServiceBean' threw exception; nested exception is java.lang.StackOverflowError
#ConfigurationProperties(prefix = "file")
public class FileStorageProperties {
private String uploadDir;
#Bean
public FileStorageService fileStorageServiceBean() throws Exception{
return new FileOnDiskStorageService(); // some random name; don't exist
}
public String getUploadDir() {
return uploadDir;
}
public void setUploadDir(String uploadDir) {
this.uploadDir = uploadDir;
}
}
Your method:
public FileStorageService fileStorageServiceBean() throws Exception{
return fileStorageServiceBean();
}
Is a recursive function. Which causes the stackOverflowError.
You get a java.lang.StackOverflowError because the method fileStorageServiceBean() is calling itself and that will result in an infinite loop. That code part can never end in this situation.
It could/should be something like:
#Bean
public FileStorageService fileStorageServiceBean() throws Exception{
return new FileOnDiskStorageService(); // some random name; don't exist
}
If you use a good IDE it will warn you about this. It's a good advice to always use a good IDE for Java and read the warnings. Also installing the plugins like SonarQube, Findbugs is really helpful to prevent for code issues.
Also the errors stacktrace will give a line number and some info where in the code the error occurs.

cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyTastTasklet'

I am developing Spring Boot Batch Example. In this example, I have created BatchJPA core module which has Entities, JPARepository and DB configurations.
This module adding into another Spring Module as dependency and in this module, I am adding code related specific batch jobs (like custom repository etc). I have total 15 batch jobs and I will be creating separate Spring Boot project with BatchJPA dependency.
10-08-2018 14:54:11.853 [main] WARN org.springframework.context.support.ClassPathXmlApplicationContext.refresh - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyTestTasklet': Initialization of bean failed; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' available
10-08-2018 14:54:11.855 [main] INFO org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener.logAutoConfigurationReport -
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
10-08-2018 14:54:11.919 [main] ERROR org.springframework.boot.diagnostics.LoggingFailureAnalysisReporter.report -
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'transactionManager' that could not be found.
Action:
Consider defining a bean named 'transactionManager' in your configuration.
Code below:
#Service
public class MyTaskTasklet implements Tasklet {
#Autowired
private MyCustomerCustomRepository myCustomerCustomRepository;
#Override
public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
List<MyTest> mydata = myCustomerCustomRepository.getElligibleData();
if (!mydata.isEmpty()) {
System.out.println("XXXXXX = " + mydata.size());
}
chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext()
.put("listOfData", mydata);
return RepeatStatus.FINISHED;
}
}
Another file:
#Component
#EnableBatchProcessing
public class MyJobLauncher {
public void executeJob() {
String[] springConfig = { "jobs/ABC.xml"};
ApplicationContext context = new ClassPathXmlApplicationContext(springConfig);
JobLauncher jobLauncher = (JobLauncher) context.getBean("jobLauncher");
Job job = (Job) context.getBean("MyJobId");
try {
JobParameters jobParameters = new JobParametersBuilder().addString("runMode", "DATA")
.addDate("date", new Date()).addLong("time", System.currentTimeMillis()).toJobParameters();
jobLauncher.run(job, jobParameters);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
}
and another file
MainApplication
#SpringBootApplication
#EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class,HibernateJpaAutoConfiguration.class})
public class MainApplication implements CommandLineRunner {
#Autowired
private MyJobLauncher jobLauncher;
public static void main(String[] args) {
SpringApplication.run(MyJobLauncher.class, args);
}
#Override
public void run(String... args) throws Exception {
jobLauncher.executeJob();
}
}

Intellij Spring: NoSuchBeanDefinitionException: No bean named 'accountDAO' available

This is driving me nuts. I have the following files, it is a very simple setup.
public class MainApp {
public static void main(String[] args) {
//read the spring config java class
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext("Config.class");
//System.out.println("Bean names: " + Arrays.toString(context.getBeanNamesForType(AccountDAO.class)));
//get the bean from spring container
AccountDAO accountDAO = context.getBean("accountDAO", AccountDAO.class);
//call the business method
accountDAO.addAccount();
//close the spring context
context.close();
}
}
Config.java:
#Configuration
#ComponentScan("com.aop")
#EnableAspectJAutoProxy
public class Config {
}
LoggingAspectDemo.java:
#Aspect
#Component
public class LoggingAspectDemo {
//this is where we add all our related advices for the logging
//let's start with an #Before advice
#Before("execution(public void addAccount())")
public void beforeAddAccountAdvice() {
System.out.println("\n=======>>>> Executing #Before advice on method addAccount() <<<<========");
}
}
AccountDAO.java
#Component
public class AccountDAO {
public void addAccount() {
System.out.println(getClass() + ": Doing my Db work: Adding an account");
}
}
Everytime I run the MainApp.java, I get:
Exception in thread "main" org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'accountDAO' available
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeanDefinition(DefaultListableBeanFactory.java:687)
at org.springframework.beans.factory.support.AbstractBeanFactory.getMergedLocalBeanDefinition(AbstractBeanFactory.java:1207)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:284)
All the files are under "com.aop" package so #ComponentScan should be scanning all the components. It looks simple enough but I can't get my hands around the problem, can anyone help me where I am going wrong?
You're invoking the constructor of AnnotationConfigApplicationContext with "Config.class" as String argument, but this constructor is actually for invoking with base packages i.e. the argument must be a package name.
Since you want to use it with the Configuration class, use the constructor which accepts Class instance instead i.e.
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);

Cucumber Spring and class configuration

I'm struggling with Cucumber and Spring configuration.
I'm writing selenium framework using Page Object Pattern, with BrowserFactory.
When I use #ComponentScan, #Component and #Autowire annotations everything works fine, but when I want to create a bit more complicated bean with #Bean annotation (BrowserFactory which registers few browser drivers) in #Configuration class it does not work, during debug I'm getting nulls on every single variable I'm trying to Autowire.
I'm using Spring 4.2.4, all cucumber dependencies in version 1.2.4.
Config:
#Configuration
public class AppConfig {
#Bean
#Scope("cucumber-glue")
public BrowserFactory browserFactory() {
BrowserFactory browserFactory = new BrowserFactory();
browserFactory.registerBrowser(new ChromeBrowser());
browserFactory.registerBrowser(new FirefoxBrowser());
return browserFactory;
}
#Bean(name = "loginPage")
#Scope("cucumber-glue")
public LoginPage loginPage() throws Exception {
return new LoginPage();
}
#Bean(name = "login")
#Scope("cucumber-glue")
public Login login() {
return new Login();
}
}
POP:
public class LoginPage extends Page {
public LoginPage() throws Exception {
super();
}
...
}
Page:
public class Page {
#Autowired
private BrowserFactory browserFactory;
public Page() throws Exception{
...
}
}
Login:
public class Login {
#Autowired
private LoginPage loginPage;
public Login(){}
...
}
Steps:
#ContextConfiguration(classes = {AppConfig.class})
public class LoginSteps {
#Autowired
Login login;
public LoginSteps(){
}
#Given("^an? (admin|user) logs in$")
public void adminLogsIn(Login.User user) throws Exception {
World.currentScenario().write("Logging in as " + user + "\n");
login.as(user);
}
}
Error:
cucumber.runtime.CucumberException: Error creating bean with name 'LoginSteps': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: Login LoginSteps.login; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'login': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private LoginPage Login.loginPage; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'loginPage' defined in AppConfig: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [LoginPage]: Factory method 'loginPage' threw exception; nested exception is java.lang.NullPointerException
And now for the fun part...
BrowserFactory in World class is properly Autowired!!
World:
public class World {
#Autowired
private BrowserFactory browserFactory;
...
}
So I'll answer my own question:)
Issue was that I was calling BrowserFactory inside of Page constructor.
Looks like this bean was not yet created and was causing NPEs.
In order to fix that I:
Added #Lazy annotation to configuration (all elements that use this configuration, both defined in that class and those which will be found by Scan will be created as Lazy)
Moved call to Browser Factory to #PostConstruct method
Two more things to increase readability of Spring config:
Added #ComponentScan to configuration
Classes with no constructor parameters are annotated with #Component and #Scope("cucumber-glue") annotation so bean creation can be removed from AppConfig.class

Resources