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

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.

Related

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

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

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();
}
}

#WebMvcTest not running due to missing dependency

I want to test my controller by using #WebMvcTest. I #MockBean the dependencies of the controller but when running the test, it fails to start. The application starts correctly when running the main class.
The Test:
#RunWith(SpringRunner.class)
#WebMvcTest(MetricResource.class)
public class MetricResourceTest {
#Autowired
private MockMvc mvc;
#MockBean
private MetricService metricService;
#MockBean
private MetricMapper metricMapper;
#Test
public void test() {
}
}
The Controller:
#RestController
#RequestMapping("/api/v1/metrics")
public class MetricResource {
private final MetricService metricService;
private final MetricMapper metricMapper;
public MetricResource(MetricService metricService, MetricMapper metricMapper) {
this.metricService = metricService;
this.metricMapper = metricMapper;
}
#GetMapping
public ResponseEntity<List<MetricDto>> getMetrics(#RequestParam(required = false) List<String> fields) {
if (fields == null) {
fields = new ArrayList<>();
}
List<Metric> metrics = metricService.getMetric(fields);
List<MetricDto> dto = metricMapper.fromMetric(metrics);
return ResponseEntity.ok(dto);
}
}
The error:
Description:
Parameter 2 of constructor in com.sps.soccer.service.SoccerService required a bean named 'mongoTemplate' that could not be found.
Action:
Consider defining a bean named 'mongoTemplate' in your configuration.
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'soccerService' defined in file [K:\home\projects\stable\sps-backend\sps-soccer\target\classes\com\sps\soccer\service\SoccerService.class]: Unsatisfied dependency expressed through constructor parameter 2; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'soccerAnalysisRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'soccerAnalysisRepository': Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'mongoTemplate' available
The SoccerService has a dependency on SoccerAnalysisRepository which is a MongoRepository. I don't understand why the SoccerService is created by the test since #Service are not scanned by #WebMvcTest.
The application is a Maven multi modules, so I has to explicitly configure the component scanning and repository.
#SpringBootApplication
#ComponentScan(basePackages = {"com.sps.soccer", "com.sps.sdql", "com.sps.core", "com.sps.web"},
excludeFilters = {
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.sdql.configuration.ClockConfiguration.class),
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.soccer.configuration.ClockConfiguration.class),
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.sdql.configuration.RestConfiguration.class),
#ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = com.sps.soccer.configuration.RestConfiguration.class)
})
#EnableMongoRepositories(basePackages = {"com.sps.soccer", "com.sps.sdql", "com.sps.core"})
public class SpsWebApplication {
public static void main(String[] args) {
SpringApplication.run(SpsWebApplication.class, args);
}
}
You must move all area-specific configuration, like #ComponentScan and #EnableMongoRepositories, to a separate #Configuration file. It's important not to litter the application’s main class with configuration settings that are specific to a particular area of its functionality.
More information: https://docs.spring.io/spring-boot/docs/2.0.3.RELEASE/reference/htmlsingle/#boot-features-testing-spring-boot-applications-testing-user-configuration

how to config mybatis in springboot

I have two config here:
#Configuration
public class DataConfig {
#Value("${datasource.jdbcUrl}")
private String jdbcUrl;
#Value("${datasource.username}")
private String username;
#Value("${datasource.password}")
private String password;
#Value("${datasource.driverClassName:com.mysql.jdbc.Driver}")
private String driverClassName;
#Value("${datasource.initialSize:20}")
private int initialSize;
#Value("${datasource.maxActive:30}")
private int maxActive;
#Value("${datasource.minIdle:20}")
private int minIdle;
#Value("${datasource.transactionTimeoutS:30}")
private int transactionTimeoutS;
#Value("${datasource.basePackage:com.tg.ms.mapper}")
private String basePackage;
#Value("${datasource.mapperLocations}")
private String mapperLocations;
#Bean
public DataSource dataSource() {
DruidDataSource ds = new DruidDataSource();
ds.setMaxWait(maxWait);
ds.setValidationQuery(validationQuery);
ds.setRemoveAbandoned(removeAbandoned);
ds.setRemoveAbandonedTimeout(removeAbandonedTimeout);
ds.setTestWhileIdle(testWhileIdle);
ds.setTestOnReturn(testOnReturn);
ds.setTestOnBorrow(testOnBorrow);
ds.setMinIdle(minIdle);
return ds;
}
#Bean
public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
sqlSessionFactoryBean.setDataSource(dataSource());
PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath:/mybatis/*.xml"));
return sqlSessionFactoryBean.getObject();
}
---------- Another Config -------------
#Configuration
#AutoConfigureAfter(DataBaseConfig.class)
public class MapperScannerConfig {
#Value("${datasource.basePackage:com.tg.ms.mapper}")
private String basePackage;
#Bean
public MapperScannerConfigurer BPMapperScannerConfigurer() {
System.out.println("mapper--1.----******----"+basePackage+"----*******");
MapperScannerConfigurer mapperScannerConfigurer = new MapperScannerConfigurer();
mapperScannerConfigurer.setBasePackage("com.tg.mapper");
mapperScannerConfigurer.setSqlSessionFactoryBeanName("sqlSessionFactoryBean");
return mapperScannerConfigurer;
}
}
Can I put#Bean public MapperScannerConfigurer BPMapperScannerConfigurer() into DataConfig? I try but print:
Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'testController': Unsatisfied dependency expressed through field 'testMapper'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testMapper' defined in file [/Users/twogoods/codesource/mainetset/target/classes/com/tg/mapper/TestMapper.class]: Cannot resolve reference to bean 'sqlSessionFactoryBean' while setting bean property 'sqlSessionFactory'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactoryBean' defined in class path resource [com/tg/config/DataConfig.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.apache.ibatis.session.SqlSessionFactory]: Factory method 'sqlSessionFactoryBean' threw exception; nested exception is java.lang.NullPointerException
MapperScannerConfig init earlier than DataConfig, I get it from print log,#Value("${datasource.basePackage:com.tg.ms.mapper}") private String basePackage;can not get value(in DataConfig can get),I use #AutoConfigureAfter is useless,MapperScannerConfig is also eariler, I can not config mapper basePackage
log:Cannot enhance #Configuration bean definition 'BPMapperScannerConfigurer' since its singleton instance has been created too early. The typical cause is a non-static #Bean method with a BeanDefinitionRegistryPostProcessor return type: Consider declaring such methods as 'static'.
I got the same problem. MapperScannerConfigurer is initialized too early in spring framework and ,i think it causes the annotation #AutoConfigureAfter become useless.
So i solve it like : avoid the use of MapperScannerConfigurer:
two ways:
just use #MapperScan("com.a.b.package")
use annotation #org.apache.ibatis.annotations.Mapper in your mybatis mapper interface.

How to create a Spring bean for apache logging Log class?

I'd like to create an autowired bean in a Dao class in order to do logging opperations. My way was hitherto static final statement like this:
private static final Log log = LogFactory.getLog(LoggedClass.class);
But now I'm trying to use IoC to turn classes decoupled.
If just add configuration in pom.xml and try to do sth like
#Autowired
Log log;
I receive an error message:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'funciDaoImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: org.apache.commons.logging.Log br.com.bb.dirco.dao.impl.FunciDaoImpl.log; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'log' defined in class path resource [com/company/project/util/PersistenceConfig.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [java.lang.Class]: : No qualifying bean of type [java.lang.Class] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [java.lang.Class] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
In order to get a logger, I had to provide a class to getLog method on LogFactory class and attribute it to Log instance. There's a way to do it using #Autowired Spring IoC? Thanks!
You can inject only those objects which are managed/created by Spring container. You have to register your bean (or factory method creating the bean) with container (with annotations like #Component/#Singleton/... or directly in xml)
In your case it's not very applicable since you have to have many different types (for every class) of logger objects provided by Spring and then when you inject they would have to be identified by different name/type for every class.
P.S. I don't see any problem using it the way you use it now
Where I work we have implemented support for #Autowired SLF4J Loggers using Springs BeanPostProcessor.
First you need to define an Logger placeholder bean in your application context. This bean is going to be injected by Spring into all bean with a #Autowired Logger field.
#Configuration
public class LoggerConfig {
#Bean
public Logger placeHolderLogger() {
return PlaceHolder.LOGGER;
}
#Bean
public AutowiredLoggerBeanPostProcessor loggerPostProcessor() {
return new AutowiredLoggerBeanPostProcessor();
}
}
Then you an AutowiredLoggerBeanPostProcessor which inspects all beans, indetify bean that contain Logger fields annotated with #Autowired (at this point should contain a reference to the Logger placeholder bean), create a new Logger for the partilcar bean an assigned it to the fields.
#Component
public class AutowiredLoggerBeanPostProcessor implements BeanPostProcessor, PriorityOrdered {
#Override
public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
attachLogger(bean);
return bean;
}
#Override
public Object postProcessBeforeInitialization(final Object bean, String beanName) throws BeansException {
attachLogger(bean);
return bean;
}
private void attachLogger(final Object bean) {
ReflectionUtils.doWithFields(bean.getClass(), new FieldCallback() {
public void doWith(Field field) throws IllegalArgumentException, IllegalAccessException {
if (Logger.class.isAssignableFrom(field.getType()) &&
(field.isAnnotationPresent(Autowired.class) ||
field.isAnnotationPresent(Inject.class))) {
ReflectionUtils.makeAccessible(field);
if (field.get(bean) == PlaceHolder.LOGGER) {
field.set(bean, LoggerFactory.getLogger(bean.getClass()));
}
}
}
});
}
#Override
public int getOrder() {
return HIGHEST_PRECEDENCE;
}
}

Resources