Spring Boot + Groovy + JPA, failed to inject JpaRepository - spring-boot

Here is my app.groovy code:
package org.test
import javax.persistence.*
import org.springframework.data.jpa.repository.JpaRepository
#Grab('spring-boot-starter-data-jpa')
#Grab('mysql-connector-java')
#Entity
#Table (name="owner")
class Owner {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
Long ownerId;
#Column(name = 'Name')
String name;
#Column(name = 'DateOfBirth')
Date dateOfBirth;
#Column(name = 'Address')
String address;
#Override
String toString() {
return String.format(
"Owner[id=%d, Name='%s', DateOfBirth='%s']",
id, name, dateOfBirth);
}
}
interface OwnerRepository extends JpaRepository<Owner, Long> {
List<Owner> findByName(String name);
}
class Runner implements CommandLineRunner {
#Autowired
private DataSource ds;
#Autowired
private OwnerRepository repository
void run(String... args) {
for (owner in repository.findAll()) {
println owner
}
}
}
application.properties code:
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/ng4
spring.datasource.username=user_name
spring.datasource.password=********
spring.jpa.show-sql=false
spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.database=MYSQL
spring.jpa.hibernate.ddl-auto=validate
After running $ spring run app.groovy, I got following error messages:
Field repository in org.test.Runner required a bean of type 'org.test.OwnerRepository' that could not be found.
Action:
Consider defining a bean of type 'org.test.OwnerRepository' in your configuration.
...
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'runner': Unsatisfied dependency expressed through field 'repository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.test.OwnerRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
I have tried to test inject JdbcTemplate using the same code statement, and it works fine, so I have no idea what's wrong in those code.
Please give me some suggestions, thanks very much !!

Actually the problem is that you also don't have #SpringBootApplication on top of your Runner class.
you're missing #Repository annotation on top of your OwnerRepository. That might be it.

Related

Error while creating spatial entity with Hibernate and GeometrySerializer : No qualifying bean of type 'GeometryParser<?>'

I tried to create a simple application with a geometry persistent layer (Spring boot with hibernate-spatial)
Here is my Entity class :
// Annotations from lombok project
#NoArgsConstructor
#AllArgsConstructor
#Data
#Builder
#Entity
#Table(name = "persistent_geometry")
public class PersistentGeometry implements Serializable {
#Id
#GeneratedValue(generator = "uuid2")
#GenericGenerator(name = "uuid2", strategy = "org.hibernate.id.UUIDGenerator")
#Column(name = "id", columnDefinition = "VARCHAR(255)")
private UUID id;
#JsonSerialize(using = GeometrySerializer.class)
#JsonDeserialize(using = GeometryDeserializer.class)
#Column(name = "geometry", columnDefinition = "geometry(Polygon,4326)")
private Polygon geometry;
}
Here is my repository interface
public interface PersistentGeometryService extends CrudRepository<PersistentGeometry, UUID> {}
Here is my controller class
#RestController
public class PersistenGeometryController {
#Autowired
private PersistentGeometryService persistentGeometryService;
#PostMapping(value="/persistentGeometry")
public ResponseEntity createNewGeom(#RequestBody PersistentGeometry persistentGeometry) {
PersistentGeometry newGeom = persistentGeometryService.save(persistentGeometry);
var headers = new HttpHeaders();
headers.add("Location", "/persistentGeometry/" + newGeom.getId().toString() );
return new ResponseEntity(headers, HttpStatus.CREATED);
}
}
However, when i do a POST request with this payload :
{
"geometry" : "POLYGON((<Some Coordinates here>))"
}
Or its GeoJSON version :
{
"geometry" : {"type":"Polygon","coordinates":[[[<Some Coordinates here>]]]}
}
I got this error from my spring app (com.geomdemo.peristentgeometry is my base package name) :
Failed to evaluate Jackson deserialization for type [[simple type,
class com.geomdemo.peristentgeometry.model.PersistentGeometry]]:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name
'com.bedatadriven.jackson.datatype.jts.serialization.GeometryDeserializer':
Unsatisfied dependency expressed through constructor parameter 0;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
'com.bedatadriven.jackson.datatype.jts.parsers.GeometryParser'
available: expected at least 1 bean which qualifies as autowire
candidate. Dependency annotations: {}
Failed to evaluate Jackson deserialization for type [[simple type,
class com.geomdemo.peristentgeometry.model.PersistentGeometry]]:
com.fasterxml.jackson.databind.JsonMappingException: Class
com.bedatadriven.jackson.datatype.jts.serialization.GeometryDeserializer
has no default (no arg) constructor
I found a suggestion here to add a #Bean of type JtsModule so I did this :
#Configuration
public class JacksonConfig {
#Bean
public JtsModule jtsModule() {
return new JtsModule();
}
}
But it didn't help in my case....It seems clear that SPring boot is looking for a valid Beans of type GeometryParser...But How to implement such a Bean...did not found any documentation or example on how to perform this.
I was having the same problem with a deserializer, I was missing the default no arguments constructor after I added that constructor, everything worked fine.
I see that you have the Lombok annotations, I tried with those as well, but I was getting compilation errors, but I think is because my class is extends StdDeserializer.

Parameter 0 of constructor in [] required a bean of type [] that could not be found

Error: Parameter 0 of constructor in com.tw.api.service.impl.BookServiceImpl required a bean of type 'com.tw.api.repository.BookRepository' that could not be found.
Exception: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookController' defined in file [/Users/rashdul.ehasan/Projects/boot-camp/api/target/classes/com/tw/api/controller/BookController.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bookServiceImpl' defined in file [/Users/rashdul.ehasan/Projects/boot-camp/api/target/classes/com/tw/api/service/impl/BookServiceImpl.class]: Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.tw.api.repository.BookRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations
Any idea on how to fix this?
I have excluded the default auto configuration...
#SpringBootApplication(exclude = {
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
MongoAutoConfiguration.class,
MongoDataAutoConfiguration.class})
public class ApiApplication {
I have written a factory bean class for mongo but it does not seem to reach there.
#Configuration
#ConditionalOnProperty(prefix = "spring", name = "db.dialect", havingValue = "mongo", matchIfMissing = true)
#EnableMongoRepositories(
repositoryFactoryBeanClass = ApiMongoRepositoryFactoryBean.class,
basePackages = "com.tw.api.repository")
public class ApiMongoRepositoryConfig {
#Value("${spring.data.mongodb.uri}")
private String uri;
private static final Logger LOGGER = LoggerFactory.getLogger(ApiMongoRepositoryConfig.class);
public ApiMongoRepositoryConfig() {
LOGGER.info("Repository Configuration: " + ApiMongoRepositoryConfig.class);
}
#Bean
public MongoClient mongoClient() {
return new MongoClient(new MongoClientURI(uri));
}
}
Packages:
BookController: package com.tw.api.controller;
BookService: package com.tw.api.service;
BookServiceImpl: package com.tw.api.service.impl;
BookRepository: package com.tw.api.repository;
ApiMongoRepository: package com.tw.api.repository.base;
ApiMongoRepositoryConfig: package com.tw.api.config;
ApiMongoRepositoryFactoryBean: package com.tw.api.helper;
ApiApplication: package com.tw.api;
Here is the link to the code base, https://github.com/er310/boot-camp/tree/master/api
You have your Book class marked as a JPA entity:
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "book")
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonIgnoreProperties(ignoreUnknown = true)
public class Book extends AbstractEntity {
But you are only creating Mong repositories with #EnableMongoRepositories.
You need to make up your mind if you want to use MongoDb with Spring Data Mongo or a relational database with JPA + Spring Data JPA.

"I need required a bean of type" Error : Spring-boot

I get an error when I try to execute SpringBoot. because I need a " bean ", I don't understand why I get this, I have all annotations
17-09-2018 12:24:53.905 [restartedMain] WARN o.s.b.c.e.AnnotationConfigEmbeddedWebApplicationContext.refresh - Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterController': Unsatisfied dependency expressed through field 'pgService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'parameterServiceImp': Unsatisfied dependency expressed through field 'pgRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'es.my.repository.ParameterRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
With more error :
APPLICATION FAILED TO START
Description:
Field pgRepository in es.service.ParameterServiceImp required a bean of type 'es.repository.ParameterRepository' that could not be found.
Action:
Consider defining a bean of type 'es.repository.ParameterRepository' in your configuration.
I have in my controller -> with #Autowired
#RestController
#RequestMapping(value = { "/param" })
#CrossOrigin
public class ParameterController {
#Autowired
ParameterService pgService;
#RequestMapping(method = RequestMethod.GET, value = "/get", produces =
MediaType.APPLICATION_JSON_VALUE)
public List<Parameter> getAllParameters() {
List<Parameter> list = pgService.selectAll();
return list;
}
In my service -> I don't use annotations
public interface ParameterService {
public List<Parameter> selectAll();
}
Imple-> I use Service and Autowired
#Service
public class ParameterServiceImp implements ParameterService {
#Autowired
ParameterRepository pgRepository;
public List<Parameter> selectAll() {
return pgRepository.findAll());
}
}
Repository -> Here , I have querys.
public interface ParameterRepository extends CrudRepository<Parameter, String> {
}
Model ->
My POJO
#Entity
#Table(name = "Parameter")
public class Parameter {
#Id
#NotNull
#Column(name = "ID")
private String id;
#NotNull
#Column(name = "name")
private String name;
// getters setters and construct
}
I have #Entity , #Service , #Autowired but I get an error
If you use #SpringBootApplication with no basePackage specified, it will default to the current package. Just like you add #ComponentScan and #EnableJpaRepositories with no base package.
If you have set a different package to #SpringBootApplication make sure you also add #EnableJpaRepositories with proper basePackage. Repositories won't be recognized only by #ComponentScan(or declaring them as beans by any other ways explicitly or implicitly).
Try adding the next annotation.
#EnableJpaRepositories(basePackages = {"<repository-package-here>"})
is a.some.package package for your #SpingbootApplication?
other wise you need to add component scan annotation for your base package that is a.some.package

Autowiring not working in SpringBoot controller

Hi i was trying to work over an existing SpringBoot application. I created a service class and tried to autowire it in the existing controller, but when trying to build, its failing saying bean injection failed.
Cause: org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'controller': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: private
com.disooza.www.card.dispenser.service.FilaPartnerService
com.disooza.www.card.dispenser.controller.CardDispenserController.FilaPartnerService;
nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
qualifying bean of type
[com.disooza.www.card.dispenser.service.FilaPartnerService] found for
dependency: expected at least 1 bean which qualifies as autowire
candidate for this dependency. Dependency annotations:
{#org.springframework.beans.factory.annotation.Autowired(required=true)}
at
org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:334)
Following is my controller class:
#Controller
#RequestMapping(value = "/service")
public class CardController {
private static final Logger LOGGER = LoggerFactory.getLogger(CardController.class);
#Autowired
private CardDao dao;
#Autowired
private PaymentService paymentService;
#Autowired
private FilaPartnerService filaPartnerService;
FilaPartnerService is the newly created interface, and rest all autowires are working fine in this controller.
Interesting thing is when I try to place this service class in any other controller it is working fine. Any help over this issue will be appreciated, since I'm stuck with it.
This is my service interface:
#Service
public interface FilaPartnerService {
RetrievePaymentTokenResponse retrieveXXX(SupplierRequest request);
}
This is the implementation class:
#Component
public class FilaPartnerServiceImpl implements FilaPartnerService {
#Autowired
private RestTemplate restTemplate;
#Autowired
private RetrieveRequestBuilder retrieveRequestBuilder;
#Value("${filaPartner.url}")
private String filaServiceUrl;
#Override
public RetrievePaymentTokenResponse retrieveFilaPaymentToken(SupplierTokenRequest request) {
RetrievePaymentTokenResponse tokenResponse = null;
RetrievePaymentTokenRequest paymentServiceRequest = retrievePaymentTokenRequestBuilder.retrievePaymentTokenRequestBuilder(request);
try {
tokenResponse =
restTemplate.postForObject( FilaServiceUrl, paymentServiceRequest, RetrievePaymentTokenResponse.class);
} catch (RestClientException exp) {
//TO-DO return error code
}
return null;
}
}

BeanCreationException for Spring-data-jpa repository in controller

I have spring-boot-starter-data-jpa and spring-boot-starter-web. I try load List<Project> from mysql using Spring jpa but get bellow BeanCreationException in controller.
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'controller': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.project.data.spring_jpa.ProjectRepository com.project.application.Controller.repository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.project.data.spring_jpa.ProjectRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Controller.java:
...
#RestController
public class Controller {
...
#Autowired
private ProjectRepository repository;
private ProjectAccessor projectAccessor = manager.createAccessor(ProjectAccessor.class);
public void setRepository(ProjectRepository repository){
this.repository = repository;
}
#RequestMapping("/test")
#ResponseBody
public List<Project> test() {
System.out.println("mysql test");
return repository.findAll();
}
...
ProjectRepository.java:
public interface ProjectRepository extends CrudRepository<Project, Long>{
List<Project> findAll();
}
Did you write #Repository annotation on ProjectRepository
#Repository
public interface ProjectRepository extends CrudRepository<Project, Long>{
List<Project> findAll();
}
Do make sure you enabled JpaRepository on your configuration using #EnableJpaRepositories
We get this exception usually when we don't specify where to look for the JPA repositories.
So mention #EnableJpaRepositories("your repository package") where you specify #Configuration or #SpringBootApplication.
It will work fine.

Resources