Spring Data Repository Autowiring troubles - spring

Im having trouble autowiring my CrudRespository in my Controller (I am using Spring boot).
Here are my Controller,Entity & Respository implementations
Repository:
package com.nbha.micro.ratingService;
import org.springframework.data.repository.CrudRepository;
import org.springframework.stereotype.Repository;
public interface RaterDORepository extends CrudRepository<RaterDO, Long> {
public RaterDO findByRaterName();
}
Entity:
#Entity
public class RaterDO {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long raterId;
public RaterDO(){}
public RaterDO(String n) {
this.raterName = n;
}
public Long getRaterId() {
return raterId;
}
public void setRaterId(Long raterId) {
this.raterId = raterId;
}
public String getRaterName() {
return raterName;
}
public void setRaterName(String raterName) {
this.raterName = raterName;
}
private String raterName;
}
Controller:
#RestController
#RequestMapping("/raters")
public class RaterController {
#Autowired
private RaterDORepository raterDORepository;
#RequestMapping("/add")
public String addRater(#RequestParam("name") String name) {
RaterDO raterDO = new RaterDO(name);
raterDORepository.save(raterDO);
return "Rater:" + name +" saved.";
}
#RequestMapping("/allRaters")
public String getAllRaters() {
StringBuilder sb = new StringBuilder();
sb.append("|");
Iterable<RaterDO> raters = raterDORepository.findAll();
for(RaterDO rater : raters) {
sb.append(rater.getRaterName());
sb.append("|");
}
return sb.toString();
}
}
Starter class:
#EnableBinding(ConsumerChannels.class)
#ComponentScan(basePackages={"com.nbha.micro.ratingService"})
#EntityScan(basePackages={"com.nbha.micro.ratingService"})
#EnableJpaRepositories(basePackages={"com.nbha.micro.ratingService"})
#SpringBootApplication
#EnableEurekaClient
#RestController
#RequestMapping("/ratings")
public class RatingApp
{
public static void main( String[] args )
{
System.out.println( "Invoking Rating Service.." );
SpringApplication.run(RatingApp.class, args);
}
#StreamListener(ConsumerChannels.PRODUCER)
public void receiveRater(final Rater rater) {
if(rater != null) {
System.out.println("Rating received in the rating-service:" + rater.getName());
}
}
private List<Rating> ratingList = Arrays.asList(
new Rating("R101","101",5),
new Rating("R102","102",2),
new Rating("R103","101",4),
new Rating("R104","101",1)
);
#GetMapping("/all")
public List<Rating> findAllRatings() {
return this.ratingList;
}
#GetMapping("/rating-agency")
public String whichRatingAgency() {
return "Moody's";
}
#GetMapping("")
public List<Rating> findRatingsByBookId(#RequestParam String bookId) {
Rating r;
List<Rating> rList = new ArrayList<Rating>();
ListIterator iter = this.ratingList.listIterator();
while(iter.hasNext()) {
r = (Rating)iter.next();
if(r.getBookId().equals(bookId)) {
rList.add(r);
}
}
return rList;
}
}
interface ConsumerChannels {
String PRODUCER = "producer";
#Input
SubscribableChannel producer();
}
I placed all these classes in the same package (in a desparate bid to make it work)
I keep getting the following error on application startup (fails to startup).The interesting thing is that a similar setup works in another instance without using #ComponentScan #EntityScan #EnableJpaRepository annotations :)
Application startup failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'raterController': Unsatisfied dependency expressed through field 'raterDORepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'raterDORepository': Invocation of init method failed; nested exception is java.util.NoSuchElementException
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:588) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
....
Caused by: org.springframework.beans.factory.BeanCreationException:Error creating bean with name 'raterDORepository': Invocation of init method failed; nested exception is java.util.NoSuchElementException
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1628) ~[spring-beans- 4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.11.RELEASE.jar:4.3.11.RELEASE]
....
Caused by: java.util.NoSuchElementException: null
at java.util.ArrayList$Itr.next(ArrayList.java:860) ~[na:1.8.0_151]
at org.springframework.data.jpa.repository.query.ParameterMetadataProvider.next(ParameterMetadataProvider.java:122) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator$PredicateBuilder.build(JpaQueryCreator.java:302) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
at org.springframework.data.jpa.repository.query.JpaQueryCreator.toPredicate(JpaQueryCreator.java:208) ~[spring-data-jpa-1.11.7.RELEASE.jar:na]
....
Any clues will be appreciated. Here are my dependencies from pom.xml:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.7.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-config</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-eureka</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-stream</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-stream-kafka</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies`enter code here`</artifactId>
<version>Brixton.SR5</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>

public RaterDO findByRaterName(); needs a parameter, something like public RaterDO findByRaterName(String name).
Construction of the repository fails because the missing parameter prevents Spring Data to construct a proper method.

Related

Error creating bean with name 'dietaController'

So, I have a problem like this:
2020-01-30 22:54:20.059 ERROR 8040 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'dietaController': Unsatisfied dependency expressed through field 'dietaRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dietaRepository': Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.diet4you.LapkoEkaterina.Entity.Dieta
My pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.diet4you</groupId>
<artifactId>LapkoEkaterina</artifactId>
<version>1.0-SNAPSHOT</version>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.2.RELEASE</version>
</parent>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-thymeleaf -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
<version>2.2.2.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.3.2.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.3.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.16.Final</version>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
My Entity:
#Entity
#Table(name = "diety")
public class Dieta {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="DIETA_ID") private int dietaId;
#NotEmpty
#Column(unique=true, name ="DIETA_NAZWA")
private String nazwa;
#NotEmpty
#Column(name="OPIS") private String opis;
public Dieta(){ }
public Dieta (int dietaId,String nazwa, String opis )
{ this.dietaId = dietaId;
this.nazwa = nazwa;
this.opis = opis; }
public int getDietaId() {
return dietaId; }
public void setDietaId(int dietaId) {
this.dietaId = dietaId; }
public String getNazwa() {
return nazwa; }
public void setNazwa(String nazwa) {
this.nazwa = nazwa; }
public String getOpis() {
return opis; }
public void setOpis(String opis) {
this.opis = opis; }
}
My repository:
#Repository
public interface DietaRepository extends JpaRepository<Dieta, String> {
Dieta findByName (String name);
}
And my Controller:
#RestController
public class DietaController {
#Autowired
private DietaRepository dietaRepository;
#GetMapping("/dieta")
public List<Dieta> getAllNotes() {
return dietaRepository.findAll();
}
}
Application java class:
#Configuration
#SpringBootApplication
#EnableJpaRepositories
#EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" })
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
remove space here #EntityScan ( basePackages = { " com.diet4you.LapkoEkaterina" }) between " and com.diet4you...
change extends JpaRepository<Dieta, String> to extends JpaRepository<Dieta, Integer>
remove or fix Dieta findByName (String name) at repository interface, it's mistake

No qualifying bean of type available in SpringBoot Application

When running my SpringBoot application, I am getting this error:
An exception occurred while running. null: InvocationTargetException: Error creating bean with name 'bookController': Unsatisfied dependency expressed through field 'bookRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.example.experimental001.Repositories.BookRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)} -> [Help 1]
I have read through many posts regarding this error but none of them seem to fix my problem.
I have tried adding the #Controller annotation but it doesn't seem to fix the bean problem.
Controller:
#RestController
#RequestMapping("/api/books")
public class BookController {
#Autowired
private BookRepository bookRepository;
#GetMapping
public Iterable findAll() {
return bookRepository.findAll();
}
#GetMapping("/title/{bookTitle}")
public List findByTitle(#PathVariable String bookTitle) {
return bookRepository.findByTitle(bookTitle);
}
#GetMapping("/{id}")
public Book findOne(#PathVariable Long id) {
return bookRepository.findById(id)
.orElseThrow(() -> new BookNotFoundException("Book not found", null));
}
#PostMapping
#ResponseStatus(HttpStatus.CREATED)
public Book create(#RequestBody Book book) {
return bookRepository.save(book);
}
#DeleteMapping("/{id}")
public void delete(#PathVariable Long id) {
bookRepository.findById(id).orElseThrow(() -> new BookNotFoundException("Book not found", null));
bookRepository.deleteById(id);
}
#PutMapping("/{id}")
public Book updateBook(#RequestBody Book book, #PathVariable Long id) {
if (book.getId() != id) {
throw new BookIdMismatchException("error");
}
bookRepository.findById(id).
orElseThrow(() -> new BookNotFoundException("Book not found", null));
return bookRepository.save(book);
}
}
Simple Controller:
#Controller
public class SimpleController {
#Value("${spring.application.name}")
String appName;
#GetMapping("/")
public String homePage(Model model) {
model.addAttribute("appName", appName);
return "home";
}
}
Repository:
#EnableJpaRepositories
#Repository
public interface BookRepository extends CrudRepository<Book, Long> {
public List<Book> findByTitle(String title);
}
Pom:
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
Application File:
#SpringBootApplication
#ComponentScan(basePackages = BookRepository)
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
You might need to add the following to the main app class:
#ComponentScan(basePackages = "Package where the repository is located”)
Looks like your repository is in a different packer and spring context is not able to pick it up when starting up.
Please refer this doc: https://www.baeldung.com/spring-component-scanningfor

Springboot Junit test NoClassDefFoundError EntityManagerFactoryBuilderImpl

I created a springboot (2) webflux project as follow :
JPA Entity
#Entity
#Table(name = "users")
public class User implements Serializable
{
...
}
Spring repository
public interface UserRepository extends CrudRepository<User, Long>
{
}
Service
#Service
public class UserService
{
#Autowired
private UserRepository userRepo;
...
}
Webflux Handler
#Component
public class UserHandler
{
#Autowired
private UserService userService;
public Mono<ServerResponse> getUser(ServerRequest request)
{
...
}
}
RouteConfiguration
#Configuration
public class RouteConfiguration
{
#Bean
public static RouterFunction<ServerResponse> userRoutes(UserHandler userHandler)
{
return RouterFunctions.route(RequestPredicates.GET("/user"), userHandler:: getUser);
}
WebApp
#SpringBootApplication
public class WebApplication
{
public static void main(String[] args)
{
SpringApplication.run(WebApplication.class);
}
}
POM
<dependencies>
<!-- Compile -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-webflux</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.xml.bind</groupId>
<artifactId>jaxb-api</artifactId>
<version>2.3.0</version>
</dependency>
<!-- Provided -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-tomcat</artifactId>
<scope>provided</scope>
</dependency>
<!-- Runtime -->
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<scope>runtime</scope>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>io.projectreactor</groupId>
<artifactId>reactor-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Everything run fine, I can start my server and use it. I would like now to code some tests. Here is what I did :
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = WebApplication.class)
public class UserHandlerTest
{
#Autowired
private ApplicationContext context;
#MockBean
private UserService userService;
private WebTestClient testClient;
#Before
public void setUp()
{
testClient = WebTestClient.bindToApplicationContext(context).build();
}
#Test
public void testUser()
{
...
}
}
What ever I tried, I got an error with hibernate dependencies during "mvn clean install" process :
[ERROR] testUser(...UserHandlerTest) Time elapsed: 0 s <<< ERROR!
java.lang.IllegalStateException: Failed to load ApplicationContext
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl
Caused by: java.lang.NoClassDefFoundError: Could not initialize class org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl
I know JPA works in blocking way but I want to avoid to use NoSQL DB for this project. Did I miss something ? Thank you a lot for help !
Probably, you are missing details which we need to provide for datasource under src/main/resources. you can check https://github.com/hantsy/spring-reactive-sample/blob/master/boot-data-mongo/src/main/resources/application.yml. this might help you.
To test my Spring Webflux controllers, I finally use the WebFluxTest annotation. It works as expected :
#RunWith(SpringRunner.class)
#ContextConfiguration(classes = {RouteConfiguration.class, UserHandler.class})
#WebFluxTest
public class UserHandlerTest
{
#Autowired
private ApplicationContext context;
#MockBean(name="userService")
private UserService userService;
private WebTestClient testClient;
#Before
public void setUp()
{
testClient = WebTestClient.bindToApplicationContext(context).build();
}
...
As I do not use RestController annotation but functional endpoints I had to use ContextConfiguration and manually instantiate the WebTestClient.

Error while connecting to AWS SQS from spring boot

I am trying to integrate AWS SQS into my springboot app using spring cloud AWS, but keep getting this error(posted below), can someone help?
Here are my files.
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'simpleMessageListenerContainer' defined in
class path resource
[org/springframework/cloud/aws/messaging/config/annotation/SqsConfiguration.class]:
Invocation of init method failed; nested exception is
java.lang.NoSuchMethodError:
com.amazonaws.http.ExecutionContext.setCredentials(Lcom/amazonaws/auth/AWSCredentials;)V
#Configuration
public class AWSConfig {
#Value("${amazon.dynamodb.endpoint}")
private String amazonDynamoDBEndpoint;
#Value("${amazon.aws.accesskey}")
private String amazonAWSAccessKey;
#Value("${amazon.aws.secretkey}")
private String amazonAWSSecretKey;
#Value("${amazon.sqs.endpoint}")
private String amazonSqsEndpoint;
#Bean
#Primary
public AmazonSQSAsyncClient amazonSQSAsyncClient() {
AmazonSQSAsyncClient amazonSQSAsyncClient = new AmazonSQSAsyncClient(amazonAWSCredentials());
if (!StringUtils.isEmpty(amazonSqsEndpoint)) {
amazonSQSAsyncClient.setEndpoint(amazonSqsEndpoint);
}
return amazonSQSAsyncClient;
}
#Bean
public AWSCredentials amazonAWSCredentials() {
return new BasicAWSCredentials(amazonAWSAccessKey, amazonAWSSecretKey);
}
}
I am able to work with dynamodb with this but not able to connect to SQS.
I have given the correct access key, secret access key and end point in application.properties file.
#Component
#EnableSqs
public class SQSDao {
private static final Logger logger = LoggerFactory.getLogger(SQSDao.class);
private QueueMessagingTemplate queueMessagingTemplate;
#Autowired
public SQSDao(AmazonSQSAsync amazonSqs) {
this.queueMessagingTemplate = new QueueMessagingTemplate(amazonSqs);
}
public void send(String message) {
System.out.println(queueMessagingTemplate.getDefaultDestination());
queueMessagingTemplate.convertAndSend("test-queue", MessageBuilder.withPayload(message).build());
}
#SqsListener(value = "test-queue", deletionPolicy = SqsMessageDeletionPolicy.NEVER)
public void receive(String message)
{
System.out.println("message: " + message);
}
}
I was facing the same issue as described. My solution requeried implement some extra methods for the Config class:
imports [...]
#Configuration
#RefreshScope
public class SpringCloudSQSConfig {
#Value("${cloud.aws.credentials.accessKeyId:default}")
private String accessKeyId;
#Value("${cloud.aws.credentials.secretKey:default}")
private String secretKey;
#Value("${cloud.aws.region.static:default}")
private String region;
private Logger logger = LoggerFactory.getLogger(this.getClass());
#Bean
public QueueMessagingTemplate queueMessagingTemplate() {
return new QueueMessagingTemplate(amazonSQSAsync());
}
public AmazonSQSAsync amazonSQSAsync() {
return AmazonSQSAsyncClientBuilder.standard().withRegion(Regions.US_EAST_2)
.withCredentials(new AWSStaticCredentialsProvider(new BasicAWSCredentials(accessKeyId, secretKey)))
.build();
}
#Bean
public SimpleMessageListenerContainerFactory simpleMessageListenerContainerFactory() {
SimpleMessageListenerContainerFactory msgListenerContainerFactory = new SimpleMessageListenerContainerFactory();
msgListenerContainerFactory.setAmazonSqs(amazonSQSAsync());
return msgListenerContainerFactory;
}
#Bean
public QueueMessageHandler queueMessageHandler() {
QueueMessageHandlerFactory queueMsgHandlerFactory = new QueueMessageHandlerFactory();
queueMsgHandlerFactory.setAmazonSqs(amazonSQSAsync());
QueueMessageHandler queueMessageHandler = queueMsgHandlerFactory.createQueueMessageHandler();
List<HandlerMethodArgumentResolver> list = new ArrayList<>();
HandlerMethodArgumentResolver resolver = new PayloadArgumentResolver(new MappingJackson2MessageConverter());
list.add(resolver);
queueMessageHandler.setArgumentResolvers(list);
return queueMessageHandler;
}
}
And for the dependencies implemented:
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-aws-messaging</artifactId>
<version>2.2.1.RELEASE</version>
</dependency>
and adding the next property in the properties file:
spring.main.allow-bean-definition-overriding=true
I was able to fix this problem by adding the last line shown to my application.yml during local testing
spring:
autoconfigure:
exclude:
- org.springframework.cloud.aws.autoconfigure.context.ContextStackAutoConfiguration
- org.springframework.cloud.aws.autoconfigure.context.ContextRegionProviderAutoConfiguration
I resolved it by removing duplicate dependencies :
aws-xray-recorder-sdk-aws-sdk
aws-xray-recorder-sdk-aws-sdk-v2
aws-xray-recorder-sdk-aws-sdk-instrumentor
aws-xray-recorder-sdk-aws-sdk-v2-instrumentor
Before :
<!-- AWS X-Ray -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-apache-http</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-instrumentor</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2-instrumentor</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-sql-postgres</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-spring</artifactId>
</dependency>
After:
<!-- AWS X-Ray -->
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-core</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-apache-http</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-aws-sdk-v2-instrumentor</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-sql-postgres</artifactId>
</dependency>
<dependency>
<groupId>com.amazonaws</groupId>
<artifactId>aws-xray-recorder-sdk-spring</artifactId>
</dependency>
Fixed it, apparently issue was related to dependency mix up as mentioned here

Spring boot - Data Source configuration

Am using Spring Boot version 1.2.7 in my project. Planning to use Spring Data JPA and trying to setup Universal connection pool to setup Datasource for mysql JDBC.
Am getting the following error and unable to setup Datasource.
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfiguration': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1210)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:368)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1119)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1014)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:504)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:476)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:303)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:299)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:956)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:747)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:480)
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:117)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:689)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:321)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:969)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:958)
at mymantri.MymantriApplication.main(MymantriApplication.java:13)
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: private javax.sql.DataSource org.springframework.boot.autoconfigure.orm.jpa.JpaBaseConfiguration.dataSource; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:561)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:88)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:331)
... 25 more
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [javax.sql.DataSource] 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.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:1301)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1047)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:942)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:533)
... 27 more
My pom.xml,
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.test</groupId>
<artifactId>test</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test</name>
<description>Test</description>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.2.7.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<start-class>test.TestApplication</start-class>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jersey</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-mail</artifactId>
</dependency>
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
</dependency>
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ucp</artifactId>
<version>11.2.0.3</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpcore</artifactId>
<version>4.4</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
</dependency>
<dependency>
<groupId>com.eaio.uuid</groupId>
<artifactId>uuid</artifactId>
<version>3.2</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<classifier>jdk15</classifier>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-parent</artifactId>
<version>Angel.SR3</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
TestApplication.java,
#SpringBootApplication(exclude = { DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, VelocityAutoConfiguration.class })
public class TestApplication {
public static void main(String[] args) {
SpringApplication.run(TestApplication.class, args);
}
}
application-dev.properties,
application.datasource.driverClassName=com.mysql.jdbc.jdbc2.optional.MysqlDataSource
application.datasource.url=jdbc:mysql://localhost:3306/mymantri
application.datasource.username=root
application.datasource.password=root
application.datasource.initialSize=5
application.datasource.maxPoolSize=5
application.datasource.minPoolSize=5
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
spring.jpa.properties.hibernate.dialect= org.hibernate.dialect.MySQL5Dialect
DataSource class,
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "testEntityManagerFactory", transactionManagerRef = "testTransactionManager", basePackages = { "com.mymantri.web.repository"})
public class ApplicationDataSource {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(ApplicationDataSource.class);
/** The Constant TEST_SQL. */
private static final String TEST_SQL = "select 1 from dual";
/** The pooled data source. */
private PoolDataSource pooledDataSource;
/** The environment. */
private Environment environment;
/** The Constant CONNECTION_WAIT_TIMEOUT_SECS. */
private static final int CONNECTION_WAIT_TIMEOUT_SECS = 300;
/**
* Data source.
*
* #return the pool data source
*/
#Bean(name = "testDataSource")
#Primary
public PoolDataSource testDataSource() {
this.pooledDataSource = PoolDataSourceFactory.getPoolDataSource();
final String databaseDriver = environment
.getRequiredProperty("application.datasource.driverClassName");
final String databaseUrl = environment
.getRequiredProperty("application.datasource.url");
final String databaseUsername = environment
.getRequiredProperty("application.datasource.username");
final String databasePassword = environment
.getRequiredProperty("application.datasource.password");
final String initialSize = environment
.getRequiredProperty("application.datasource.initialSize");
final String maxPoolSize = environment
.getRequiredProperty("application.datasource.maxPoolSize");
final String minPoolSize = environment
.getRequiredProperty("application.datasource.minPoolSize");
try {
pooledDataSource.setConnectionFactoryClassName(databaseDriver);
pooledDataSource.setURL(databaseUrl);
pooledDataSource.setUser(databaseUsername);
pooledDataSource.setPassword(databasePassword);
pooledDataSource.setInitialPoolSize(Integer.parseInt(initialSize));
pooledDataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
pooledDataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
pooledDataSource.setSQLForValidateConnection(TEST_SQL);
pooledDataSource.setValidateConnectionOnBorrow(Boolean.TRUE);
pooledDataSource
.setConnectionWaitTimeout(CONNECTION_WAIT_TIMEOUT_SECS);
// pooledDataSource.setConnectionPoolName(poolName);
} catch (NumberFormatException e) {
LOGGER.error("Unable to parse passed numeric value", e);
} catch (SQLException e) {
LOGGER.error("exception creating data pool", e);
}
LOGGER.info("Setting up datasource for user:{} and databaseUrl:{}",
databaseUsername, databaseUrl);
return this.pooledDataSource;
}
#Bean(name = "testEntityManagerFactory")
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
lef.setDataSource(myMantriDataSource());
lef.setJpaVendorAdapter(vendorAdapter);
lef.setPackagesToScan("com.mymantri.web.domain");
lef.setJpaProperties(additionalProperties());
lef.setPersistenceUnitName("myMantriPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}
#Bean(name = "testTransactionManager")
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.enable_lazy_load_no_trans",
"true");
properties.setProperty("hibernate.show_sql","true");
return properties;
}
/**
* Sets the environment.
*
* #param environment
* the new environment
*/
#Autowired
public void setEnvironment(Environment environment) {
this.environment = environment;
}
}
Not sure, what is wrong with this config. Am i missing anything in the SpringBootConfig config.
Try to change data source registration method signature:
#Bean
public DataSource dataSource() {
BTW, it's not good idea to have local variables in configuration class. You have environment and pooledDataSource. Remove these class variables and create them locally in methods + pass them to Spring IoC container via #Bean annotation.
I suggest to change your configuration class at least this way:
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "testEntityManagerFactory", transactionManagerRef = "testTransactionManager", basePackages = { "com.mymantri.web.repository"})
public class ApplicationDataSource {
/** The Constant LOGGER. */
private static final Logger LOGGER = LoggerFactory
.getLogger(ApplicationDataSource.class);
/** The Constant TEST_SQL. */
private static final String TEST_SQL = "select 1 from dual";
/** The Constant CONNECTION_WAIT_TIMEOUT_SECS. */
private static final int CONNECTION_WAIT_TIMEOUT_SECS = 300;
/**
* Data source.
*
* #return the pool data source
*/
#Bean
public DataSource dataSource(Environment environment) {
PoolDataSource pooledDataSource = PoolDataSourceFactory.getPoolDataSource();
final String databaseDriver = environment
.getRequiredProperty("application.datasource.driverClassName");
final String databaseUrl = environment
.getRequiredProperty("application.datasource.url");
final String databaseUsername = environment
.getRequiredProperty("application.datasource.username");
final String databasePassword = environment
.getRequiredProperty("application.datasource.password");
final String initialSize = environment
.getRequiredProperty("application.datasource.initialSize");
final String maxPoolSize = environment
.getRequiredProperty("application.datasource.maxPoolSize");
final String minPoolSize = environment
.getRequiredProperty("application.datasource.minPoolSize");
try {
pooledDataSource.setConnectionFactoryClassName(databaseDriver);
pooledDataSource.setURL(databaseUrl);
pooledDataSource.setUser(databaseUsername);
pooledDataSource.setPassword(databasePassword);
pooledDataSource.setInitialPoolSize(Integer.parseInt(initialSize));
pooledDataSource.setMaxPoolSize(Integer.parseInt(maxPoolSize));
pooledDataSource.setMinPoolSize(Integer.parseInt(minPoolSize));
pooledDataSource.setSQLForValidateConnection(TEST_SQL);
pooledDataSource.setValidateConnectionOnBorrow(Boolean.TRUE);
pooledDataSource
.setConnectionWaitTimeout(CONNECTION_WAIT_TIMEOUT_SECS);
// pooledDataSource.setConnectionPoolName(poolName);
} catch (NumberFormatException e) {
LOGGER.error("Unable to parse passed numeric value", e);
} catch (SQLException e) {
LOGGER.error("exception creating data pool", e);
}
LOGGER.info("Setting up datasource for user:{} and databaseUrl:{}",
databaseUsername, databaseUrl);
return pooledDataSource;
}
#Bean
public EntityManagerFactory entityManagerFactory() {
LocalContainerEntityManagerFactoryBean lef = new LocalContainerEntityManagerFactoryBean();
JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
lef.setDataSource(myMantriDataSource());
lef.setJpaVendorAdapter(vendorAdapter);
lef.setPackagesToScan("com.mymantri.web.domain");
lef.setJpaProperties(additionalProperties());
lef.setPersistenceUnitName("myMantriPersistenceUnit");
lef.afterPropertiesSet();
return lef.getObject();
}
#Bean
public PlatformTransactionManager transactionManager() {
JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory());
return transactionManager;
}
Properties additionalProperties() {
Properties properties = new Properties();
properties.setProperty("hibernate.dialect",
"org.hibernate.dialect.MySQL5Dialect");
properties.setProperty("hibernate.enable_lazy_load_no_trans",
"true");
properties.setProperty("hibernate.show_sql","true");
return properties;
}
}
Moving the Application to com.XXXXXX.web package works.
com.XXXXXX.web.domain - for domain classes
com.XXXXXX.web.repository - for repository classes
The default annotation scanning occurs based on the Application class package name.

Resources