GraphQLName annotation - spring-boot

I am creating a simple login app using spring boot with Kotlin + GraphQL. #GraphQLName("") is not working for me.
my graphql is
schema {
query: Query
mutation: Mutation
}
type Mutation{
requestOTP(credential: String!,authType: String!): String
}
and in my kotlin
#Controller
class ResetPassword(
#Autowired val userRepository: UserRepository
): GraphQLMutationResolver {
#GraphQLName("requestOTP")
fun reset(credential: String, authType: String): String{
//codes...
}
}
But It keep saying
Error starting Tomcat context. Exception: org.springframework.beans.factory.UnsatisfiedDependencyException. Message:
Error creating bean with name 'graphQLServletRegistrationBean' defined in class path resource [graphql/kickstart/autoconfigure/web/servlet/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletRegistrationBean' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'graphQLHttpServlet' defined in class path resource [graphql/kickstart/autoconfigure/web/servlet/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLHttpServlet' parameter 0;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLServletConfiguration' defined in class path resource [graphql/kickstart/autoconfigure/web/servlet/GraphQLWebAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLServletConfiguration' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'invocationInputFactory' defined in class path resource [graphql/kickstart/autoconfigure/web/servlet/GraphQLWebAutoConfiguration.class]:
Unsatisfied dependency expressed through method 'invocationInputFactory' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLSchemaProvider' defined in class path resource [graphql/kickstart/autoconfigure/web/servlet/GraphQLWebAutoConfiguration.class]:
Unsatisfied dependency expressed through method 'graphQLSchemaProvider' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLSchema' defined in class path resource [graphql/kickstart/autoconfigure/tools/GraphQLJavaToolsAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLSchema' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schemaParser' defined in class path resource [graphql/kickstart/autoconfigure/tools/GraphQLJavaToolsAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.kickstart.tools.SchemaParser]: Factory method 'schemaParser' threw exception; nested exception is graphql.kickstart.tools.resolver.FieldResolverError: No method found as defined in schema <unknown>:44 with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment, class graphql.GraphQLContext] as the last argument), in priority order:
com.auth.test.presentation.ResetPassword.requestOTP(~credential, ~authType)
com.auth.test.presentation.ResetPassword.getRequestOTP(~credential, ~authType)
If I rename fun reset to fun requestOTP, the code compile even I put #GraphQLName("LOLnothingLOL")
. Kindly explain me why I am getting this error and how to fix it. I don't want to use requestOTP directly to have more readability.
Edit:
I am not using pom.xml instead build.gradle
Here is my gradle file.
import org.jetbrains.kotlin.gradle.tasks.KotlinCompile
plugins {
id("org.springframework.boot") version "2.7.6"
id("io.spring.dependency-management") version "1.1.0"
kotlin("jvm") version "1.7.21"
kotlin("plugin.spring") version "1.7.21"
kotlin("plugin.jpa") version "1.7.21"
}
group = "com.dagger"
version = "0.0.1"
java.sourceCompatibility = JavaVersion.VERSION_11
repositories {
mavenCentral()
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter-data-jpa")
implementation("org.springframework.boot:spring-boot-starter-web")
implementation("org.springframework.boot:spring-boot-starter-graphql")
implementation("com.graphql-java-kickstart:graphql-spring-boot-starter:14.1.0")
runtimeOnly("com.graphql-java-kickstart:graphiql-spring-boot-starter:11.1.0")
implementation("org.springframework.boot:spring-boot-starter-oauth2-client")
implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
implementation("org.springframework.boot:spring-boot-starter-security")
implementation("com.fasterxml.jackson.module:jackson-module-kotlin")
implementation ("org.springframework.boot:spring-boot-starter-log4j2")
modules {
module("org.springframework.boot:spring-boot-starter-logging") {
replacedBy("org.springframework.boot:spring-boot-starter-log4j2", "Use Log4j2 instead of Logback")
}
}
//jwt token
implementation ("io.jsonwebtoken:jjwt:0.9.1")
implementation("com.expedia.graphql:graphql-kotlin-schema-generator:1.3.4")
implementation("org.jetbrains.kotlin:kotlin-reflect")
implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8")
implementation("org.springframework.session:spring-session-core")
runtimeOnly("com.mysql:mysql-connector-j")
testImplementation("org.springframework.boot:spring-boot-starter-test")
testImplementation("org.springframework:spring-webflux")
testImplementation("org.springframework.graphql:spring-graphql-test")
testImplementation("org.springframework.security:spring-security-test")
}
tasks.withType<KotlinCompile> {
kotlinOptions {
freeCompilerArgs = listOf("-Xjsr305=strict")
jvmTarget = "11"
}
}
tasks.withType<Test> {
useJUnitPlatform()
}

Let's try to understand the issue.
Unsatisfied dependency expressed through method 'graphQLSchemaProvider' parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'graphQLSchema' defined in class path resource [graphql/kickstart/autoconfigure/tools/GraphQLJavaToolsAutoConfiguration.class]: Unsatisfied dependency expressed through method 'graphQLSchema' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'schemaParser' defined in class path resource [graphql/kickstart/autoconfigure/tools/GraphQLJavaToolsAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [graphql.kickstart.tools.SchemaParser]: Factory method 'schemaParser' threw exception; nested exception is graphql.kickstart.tools.resolver.FieldResolverError: No method found as defined in schema <unknown>:44 with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment, class graphql.GraphQLContext] as the last argument), in priority order:
In above error message if you notice last statement, issue is very clear.
nested exception is graphql.kickstart.tools.resolver.FieldResolverError: No method found as defined in schema <unknown>:44 with any of the following signatures (with or without one of [interface graphql.schema.DataFetchingEnvironment, class graphql.GraphQLContext] as the last argument), in priority order:
So the issue is, in your Controller class, Mutation method name is reset() but in GraphQl schema file method name is requestOTP(). Both should be same.
schema {
query: Query
mutation: Mutation
}
type Mutation{
requestOTP(credential: String!,authType: String!): String
}
Also I can see you are using org.springframework.boot:spring-boot-starter-graphql dependency in your build.gradle file. This dependency is enough for GraphQL implementation with Spring Boot. Please remove other GraphQL related dependencies. They are creating confusion in Spring ECO system.
Also if you writing GraphQL schema file yourself then no need to use #GraphQLName annotation.

Related

How to fix MongoTemplate --> MappingMongoConverter --> BeforeConvertCallback --> MongoTemplate circular dependency?

I am trying to create a custom Auditing callback in order to set the corresponding fields of my MongoDB documents.
This is my callback:
#Order(101)
#Component
#RequiredArgsConstructor
public class AuditingCallback implements BeforeConvertCallback<AuditingDocument<String>> {
private final AuditingConfiguration auditingConfiguration;
#Setter
#Autowired
private MongoTemplate mongoTemplate;
/**
* Entity callback method invoked before a domain object is converted to be persisted. Can return either the same or a
* modified instance of the domain object.
*
* #param entity the domain object to save.
* #param collection name of the collection.
* #return the domain object to be persisted.
*/
#Override
public AuditingDocument<String> onBeforeConvert(AuditingDocument<String> entity, String collection) {
System.out.println("Auditing Callback");
System.out.println(entity);
if(this.isNew(entity)){
System.out.println("Is new");
entity.setCreator(this.auditingConfiguration.getCurrentAuditor().orElse(null));
entity.setCreated(Instant.now());
}else{
System.out.println("Is not new");
// TODO
// Retrieve existing creator, created
Class<AuditingDocument<String>> clazz = (Class<AuditingDocument<String>>) entity.getClass();
AuditingDocument<String> existingEntity = this.mongoTemplate.<AuditingDocument<String>>findById(entity.getId(), clazz);
System.out.println("Existing Entity:");
System.out.println(existingEntity);
entity.setModifier(this.auditingConfiguration.getCurrentAuditor().orElse(null));
entity.setModified(Instant.now());
}
return entity;
}
private boolean isNew(AuditingDocument<String> entity){
return StringUtils.isBlank(entity.getId());
}
}
Now I need to find the existing entity from the DB, to keep the existing creator and created fields, hence the MongoTemplate field.
This results in a circular dependency:
┌─────┐
| mongoTemplate defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]
↑ ↓
| mappingMongoConverter defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]
↑ ↓
| auditingCallback (field private org.springframework.data.mongodb.core.MongoOperations org.myproject.configuration.database.auditing.callbacks.AuditingCallback.mongoOperations)
└─────┘
How can I break this circular dependency?
I also tried with MongoOperations but it is the same.
Note that I am already using the
allow-circular-references: true
property.
Is it not possible to load existing entities during MongoDB events callbacks?
Log 2
Cannot resolve reference to bean 'mongoTemplate' while setting bean property 'mongoOperations'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingMongoConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'mongoTemplate' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Unsatisfied dependency expressed through method 'mongoTemplate' parameter 1; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingMongoConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mappingMongoConverter' defined in class path resource [org/springframework/boot/autoconfigure/data/mongo/MongoDatabaseFactoryDependentConfiguration.class]: Initialization of bean failed; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'auditingCallback': Unsatisfied dependency expressed through field 'mongoTemplate'; nested exception is org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?
Caused by: org.springframework.beans.factory.BeanCurrentlyInCreationException: Error creating bean with name 'mongoTemplate': Requested bean is currently in creation: Is there an unresolvable circular reference?

Spring Data: Mongo Repository can not be initialized

I'm getting this strange error message when I start my spring boot service:
Caused by: org.springframework.data.mapping.PropertyReferenceException: No property storeMpi found for type Patient!
Service can't be started since this exception is raised.
My code is very straight:
public interface PatientRepository
extends MongoRepository<Patient, String>,
QuerydslPredicateExecutor<Patient>,
MPIPatientRepository
{
}
public interface MPIPatientRepository {
Patient storeMpi(Patient patient);
}
You can see, that storeMpi is a method, not an expected field of my Patient entity.
Implementation is straight as well:
#Repository
#RequiredArgsConstructor
public class MPIPatientRepository implements cat.gencat.catsalut.hes.mpi.repository.MPIPatientRepository {
private final MongoTemplate mongoTemplate;
/**
* {#inheritDoc}
*/
#Override
public Patient storeMpi(Patient patient) {
return this.mongoTemplate.save(patient);
}
I don't quite figure out what's wrong.
Formatted root CausedBy is:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'ca.uhn.fhir.spring.boot.autoconfigure.FhirAutoConfiguration$FhirRestfulServerConfiguration': Bean instantiation via constructor failed;
nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [ca.uhn.fhir.spring.boot.autoconfigure.FhirAutoConfiguration$FhirRestfulServerConfiguration$$EnhancerBySpringCGLIB$$5fe4b535]: Constructor threw exception;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'patientResourceProvider' defined in file [/home/jeusdi/projects/salut/mpi/hes-mpi-fhir-mongodb/target/classes/cat/gencat/catsalut/hes/mpi/providers/PatientResourceProvider.class]: Unsatisfied dependency expressed through constructor parameter 0;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'patientService' defined in file [/home/jeusdi/projects/salut/mpi/hes-mpi-fhir-mongodb/target/classes/cat/gencat/catsalut/hes/mpi/service/PatientService.class]: Unsatisfied dependency expressed through constructor parameter 2;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'patientRepository' defined in cat.gencat.catsalut.hes.mpi.repository.PatientRepository defined in #EnableMongoRepositories declared on MongoRepositoriesRegistrar.EnableMongoRepositoriesConfiguration: Invocation of init method failed;
nested exception is org.springframework.data.repository.query.QueryCreationException: Could not create query for public abstract cat.gencat.catsalut.hes.mpi.model.Patient cat.gencat.catsalut.hes.mpi.repository.MPIPatientRepository.storeMpi(cat.gencat.catsalut.hes.mpi.model.Patient)! Reason: No property storeMpi found for type Patient!;
nested exception is org.springframework.data.mapping.PropertyReferenceException: No property storeMpi found for type Patient!
Any ideas?

Why creating been in Spring occurs with error?

Hello I am creating program which will communicate and send information using channel. When I run program it doesn't work.
Errors:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-05-02 13:47:37.938 ERROR 12584 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'helloWorldQueueProducer' defined in file [C:\workspace\target\classes\edu\producer\HelloWorldQueueProducer.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'jmsTemplate' defined in class path resource [org/springframework/boot/autoconfigure/jms/JmsAutoConfiguration$JmsTemplateConfiguration.class]: Unsatisfied dependency expressed through method 'jmsTemplate' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'jmsConnectionFactory' defined in class path resource [org/springframework/boot/autoconfigure/jms/artemis/ArtemisConnectionFactoryConfiguration$SimpleConnectionFactoryConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.jms.connection.CachingConnectionFactory]: Factory method 'cachingJmsConnectionFactory' threw exception; nested exception is java.lang.IllegalStateException: Unable to create ActiveMQConnectionFactory
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:800) ~[spring-beans-5.3.5.jar:5.3.5]
#Component
#RequiredArgsConstructor
public class HelloWorldQueueProducer {
private final JmsTemplate jmsTemplate;
#Scheduled(fixedRate = 2000)
public void sendHello() {
HelloMessage message = HelloMessage.builder()
.id(HelloMessage.nextId())
.createdAt(LocalDateTime.now())
.message("Hello world!")
.build();
jmsTemplate.convertAndSend(JmsConfig.QUEUE_HELLO_WORLD, message);
System.out.println("HelloWorldQueueProducer.sendHello - sent message: " + message);
}
}
Not quite sure about it, but have you defined the necessary properties in your application.properties? You need to set them like this i. e.
spring.artemis.mode=native
spring.artemis.host=localhost
spring.artemis.port=61616
spring.artemis.user=developer
spring.artemis.password=developer
jms.queue.destination=myqueue
Otherwise the autoconfiguration of spring boot wouldn't bootstrap the necessary beans. I had this problem once.

Spring boot application gives "unable to start tomcat" exception with spring-boot-starter-actuator

I had my spring-boot application, with spring-boot-starter-web, then I added spring-boot-starter-actuator to gradle file. There is no compilation error. But when i try to run the server it gives the following exception.
my build.gradle content (only the main ones included )
plugins {
id 'org.springframework.boot' version '2.1.3.RELEASE'
} ...........
compile "org.springframework.boot:spring-boot-starter-actuator"
compile group: 'io.micrometer', name: 'micrometer-registry-prometheus', version: '1.1.3' .........
my application.properties content
server.port = 2128
spring.couchbase.env.timeouts.connect=10000
spring.couchbase.env.timeouts.query=180000
spring.couchbase.env.timeouts.view=20000
spring.couchbase.bootstrap-hosts=localhost
spring.couchbase.bucket.name=localdb
spring.couchbase.bucket.password=*****
spring.data.couchbase.repositories.type=auto
spring.data.couchbase.auto-index=true
server.compression.enabled=true
server.compression.mime-types=application/json,text/plain
spring.servlet.multipart.enabled=true
spring.servlet.multipart.maxFileSize=50MB
spring.servlet.multipart.maxRequestSize=50MB
my Application.java
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
Gives the following exception while starting the server.
org.springframework.context.ApplicationContextException: Unable to start web server;
nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource
WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException:
Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception;
nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource
org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 1;
nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthIndicatorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthIndicatorAutoConfiguration.class]: Bean instantiation via factory method failed
Any helpful hints?
I was finally able to start the application after I turned off default health checks via the following entry in application.properties file
management.health.defaults.enabled=false

Junit in Spring Boot keeps failing

I have very simple SpringBoot Junit but it keeps failing.
#RunWith(SpringRunner.class)
//#SpringBootTest
#WebMvcTest(TokenServiceImpl.class)
public class TokenTest {
#Test
public void getOauthToken()
{
System.out.println( " done test");
}
my TokenServiceImpl class has
public class TokenServiceImpl implements TokenService{
public String getToken() throws RuntimeException{
return " Token returned" ;
}
I get the below error : -Snippet
2019-11-27 19:12:45.884 WARN 15864 --- [ main]
o.s.w.c.s.GenericWebApplicationContext : Exception encountered
during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'runApplication': Unsatisfied dependency
expressed through field 'job'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'job' defined in class path resource
[com/mycompany/project1/batch/configurations/BatchBDREntityConfig.class]:
Unsatisfied dependency expressed through method 'job' parameter 4;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'batchDBWriter': Unsatisfied dependency
expressed through field 'BDREntityRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Field BDREntityRepository in
com.mycompany.project1.batch.services.BatchDBWriter required a bean of
type 'com.mycompany.project1.batch.repositories.BDREntityRepository'
that could not be found.
Consider defining a bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository' in
your configuration.
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'runApplication': Unsatisfied dependency
expressed through field 'job'; nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'job' defined in class path resource
[com/mycompany/project1/batch/configurations/BatchBDREntityConfig.class]:
Unsatisfied dependency expressed through method 'job' parameter 4;
nested exception is
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'batchDBWriter': Unsatisfied dependency
expressed through field 'BDREntityRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'batchDBWriter': Unsatisfied dependency
expressed through field 'BDREntityRepository'; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
Caused by:
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.mycompany.project1.batch.repositories.BDREntityRepository'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
My main method has following
#SpringBootApplication
#ComponentScan(basePackages= {"com.mycompany.project1"})
public class RunApplication{
private static final Logger logger = Logger.getLogger(BatchController.class);
#Autowired
JobLauncher jobLauncher;
#Autowired
Job job;
/*
* jmxBean will get loaded when this managed bean is called from RMI, and it will fire batch execution
*/
public static void main(String[] args){
ApplicationContext app = SpringApplication.run(RunApplication.class, args);
logger.debug("Batch Application has been started...");
BatchController controller = app.getBean(BatchController.class);
//Start batch process when application starts or restart, its optional call and can be commented out
//as we have JMX to expose load method on demand
//BatchController batch = new BatchController();
controller.startBatchProessFromMain();
}
}
#Component
public class BatchDBWriter implements ItemWriter<BDREntity> {
private static final Logger logger = Logger.getLogger(BatchDBWriter.class);
#Autowired
private BDREntityRepository bDREntityRepository;
/*
* this method call the JPArepository's saveAll
* function and saves all the list of bdrEntitiesat a time.
*/
#Override
public void write(List<? extends BDREntity> bdrEntities) throws Exception {
bDREntityRepository.saveAll(bdrEntities);
}
}
How can i fix my Junit ?
You are using #WebMvcTest that is a test-slice annotation. It's specifically intended for testing the WebMvc-related components in your application and is a form of integration test.
You've said in the comments that you're not trying to integration test your application. In that case, you should not be using #SpringBootTest or any of the other #…Test annotations that are provided by Spring Boot.
Assuming that your goal is to unit test TokenServiceImpl, I'd expect your test class to look something like this:
public class TokenTest {
private final TokenServiceImpl tokenService = new TokenServiceImpl();
#Test
public void getOauthToken() {
String token = this.tokenService.getToken();
// Assertions to check the token go here
}
}

Resources