Skip to content
Advertisement

Java Spring Boot: Dependency Injection error: Change 1st parameter of abstract method to Optional

I am trying to use dependency injection in Java Spring Boot. Receiving Error below in controller in this line. productService.updateProduct(product);

Error: Change 1st parameter of abstract method from Product to Optional

How can this be resolved?

public class Product {
    @Getter @Setter public @Id @GeneratedValue Long productId;
    @Getter @Setter public String productName;
    @Getter @Setter public String productDescription;
    Product() {}

    Product(String productName, String productDescription) {
        this.productName = productName;
        this.productDescription = productDescription;
    }
}

Interface:

public interface IProductService {
    public Product updateProduct(Product product);
}

Service:

@Service
public class ProductService implements IProductService {
    @Override
    public Product updateProduct(Product product){
        product.productName = "test12345";
        return product;
    }
}

Controller:

class ProductController {
    ProductRepository repository;
    @Autowired IProductService productService;

    ProductController(IProductService productService, ProductRepository repository) {
        this.productService = productService;
        this.repository = repository;
    }

    @GetMapping("/products/{id}")
    Product one(@PathVariable Long id) {
        var product = repository.findById(id);
        var finalProduct = productService.updateProduct(product); // error in this line
        return finalProduct;
    }

Advertisement

Answer

And check whether your Repository class return Optional<Product>. because findbyId return type of optional. Then your have to use like below.

Optional<Product> product = repository.findById(id);

And Better to add @Autowire @Controller annotation no need constructor.

@Controller
class ProductController {
@Autowired
private ProductRepository repository;

@Autowire
private IProductService productService;

}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement