Unsatisfied dependency Expressed through field 'cartRepository'

Asked

Viewed 55 times

0

Good afternoon to everyone, I am taking a Spring course and using Redis, but I came across a mistake that has taken me many hours of study and so far I have not been able to solve it. Someone would have some idea what’s wrong. Follow the code:

Exception:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'cartController': Unsatisfied dependency expressed through field 'cartRepository';

Configuration:

package com.dio.shoppingcart.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.repository.configuration.EnableRedisRepositories;
import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


@Configuration
@EnableRedisRepositories
public class RedisConfig {

    @Bean
    public JedisConnectionFactory connectionFactory() {
        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName("localhost");
        configuration.setPort(6379);
        return new JedisConnectionFactory(configuration);
    }

    @Bean
    public RedisTemplate<String, Object> template() {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory());
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new JdkSerializationRedisSerializer());
        template.setValueSerializer(new JdkSerializationRedisSerializer());
        template.setEnableTransactionSupport(true);
        template.afterPropertiesSet();
        return template;
    }

Controller:

package com.dio.shoppingcart.controller;

import com.dio.shoppingcart.model.Cart;
import com.dio.shoppingcart.model.Item;
import com.dio.shoppingcart.repository.CartRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Optional;


@RestController
@RequestMapping(value = "/cart")
public class CartController {

    @Autowired
    private CartRepository cartRepository;


    @GetMapping(value = "/{id}")
    public Cart addItem(@PathVariable("id") Integer id, @RequestBody Item item){
        Optional<Cart> savedCart = cartRepository.findById(id);
        Cart cart;
        if(savedCart.equals(Optional.empty())){
            cart = new Cart(id);
        }else{
            cart = savedCart.get();
        }
        cart.getItems().add(item);
        return cartRepository.save(cart);
    }

    @GetMapping(value = "/{id}")
    public Optional<Cart> findById(@PathVariable("id") Integer id){

        return cartRepository.findById(id);
    }

    @DeleteMapping(value = "/{id}")
    public void clear(@PathVariable("id") Integer id){

        cartRepository.deleteById(id);
    }
}

Model:

package com.dio.shoppingcart.model;


import org.springframework.data.annotation.Id;
import org.springframework.data.redis.core.RedisHash;

import java.util.ArrayList;
import java.util.List;

@RedisHash("cart")
public class Cart {
    @Id
    private Integer id;
    private List<Item> items;

    public Cart(){

    }

    public Cart(Integer id){
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public List<Item> getItems() {
        if(items == null){
            items = new ArrayList<>();
        }
        return items;
    }

    public void setItems(List<Item> items) {
        this.items = items;
    }
}

package com.dio.shoppingcart.model;

import org.springframework.data.redis.core.RedisHash;

@RedisHash("item")
public class Item {
    private Integer productId;
    private Integer amount;

    public Integer getProductId() {
        return productId;
    }

    public void setProductId(Integer productId) {
        this.productId = productId;
    }

    public Integer getAmount() {
        return amount;
    }

    public void setAmount(Integer amount) {
        this.amount = amount;
    }
}

Repository:

package com.dio.shoppingcart.repository;

import com.dio.shoppingcart.model.Cart;
import org.springframework.data.repository.CrudRepository;




public interface CartRepository extends CrudRepository<Cart, Integer> {
}

Main:

package com.dio.shoppingcart;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ShoppingCartApplication {

    public static void main(String[] args) {
        SpringApplication.run(ShoppingCartApplication.class, args);
    }

}

build.Gradle:

plugins {
    id 'org.springframework.boot' version '2.5.3'
    id 'io.spring.dependency-management' version '1.0.11.RELEASE'
    id 'java'
}

group = 'com.dio'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-actuator'
    implementation 'org.springframework.boot:spring-boot-starter-data-redis'
    implementation 'org.springframework.boot:spring-boot-starter-web'
    implementation group: 'redis.clients', name: 'jedis', version: '3.3.0'
    testImplementation 'org.springframework.boot:spring-boot-starter-test'
}

test {
    useJUnitPlatform()
}

  • Welcome! What’s going on: he’s not able to create the Repository to be injected/used in cartController. Is there anything else in the log? It would be interesting for you to post the entire log because it might give signals of what might be happening. For example, if you are having problems connecting with redis (authentication data, port, anything), maybe the full log will help in this sense.

3 answers

0

I believe some JPA configuration is missing.

Try putting @EnableJpaRepositories in its main class or configuration bean. You may still need to indicate the package, e.g..: @EnableJpaRepositories(basePackages = "com.dio.shoppingcart.model")

It is also possible that the dependency of Spring JPA "spring-boot-Starter-data-jpa is missing"

-1

Hello, first when you have dependency injection errors always check your Bs if they are annotated correctly and post complete error log.

I would say that your problem is the absence of @Repository in the class "Cartrepository", return if successful with this adjustment.

See you around.

-1

Welcome! It would be interesting as it has already been proposed by the leandro who posts the entire log, at the beginning of the error this lacking dependency on your project

Browser other questions tagged

You are not signed in. Login or sign up in order to post.