I keep looking at my codes all day along, I can't find the cause. The repository (#Repository) is working just fine, it's the #Service field that I keep failing get it autowired, I keep struggling since everything looks fine
The dispatched servlet:
<mvc:annotation-driven />
<context:component-scan base-package="com" />
com.repository
Repo.java
package com.repository;
import com.domain.Student;
import java.util.List;
public interface Repo { public List<Student> getAllSiswa(); }
RepoImplement.java
import com.domain.Student;
import java.util.ArrayList;
import java.util.List;
import org.springframework.stereotype.Repository;
#Repository
public class RepoImplement implements Repo {
List<Student> ls = new ArrayList<>();
public RepoImplement(){
Student s1 = new Student();
s1.setNama("paul");
Student s2 = new Student();
s2.setNama("robert");
ls.add(s1);
ls.add(s2);
}
#Override
public List<Student> getAllSiswa() {
return this.ls;
}
}
package com.service;
Serve.java
import com.domain.Student;
import java.util.List;
public interface Serve {
void changeName(String namaBaru);
public List<Student> newList();
}
I'm suspecting there's something wrong over here
ServeImplement.java
import com.domain.Student;
import com.repository.Repo;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class ServeImplement implements Serve {
#Autowired
public Repo repo;
List<Student> s = repo.getAllSiswa(); // THIS IS SUSPECTING ME.
#Override
public void changeName(String namaBaru) {
s.get(0).setNama(namaBaru); // get first Student, then update its name.
}
#Override
public List<Student> newList() {
return this.s;
}
}
controller2.java (it's the mapping request for serving student)
package com.controlller;
import com.domain.Student;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.service.Serve;
#Controller
public class controller2 {
#Autowired
public Serve serv;
#RequestMapping("/changename")
public ModelAndView sdaf() {
serv.changeName("New name");
List<Student> list = serv.newList();
return new ModelAndView("page2", "out", list);
}
}
The error:
Error creating bean with name 'controller2': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.BeanCreationException: Could not
autowire field: public com.service.Serve
com.controlller.controller2.serv; nested exception is
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'serveImplement' defined in file
[C:\Users\hans\Documents\NetBeansProjects\WebApplication2\build\web\WEB-INF\classes\com\service\ServeImplement.class]:
Instantiation of bean failed; nested exception is
org.springframework.beans.BeanInstantiationException: Could not
instantiate bean class [com.service.ServeImplement]: Constructor threw
exception; nested exception is java.lang.NullPointerException
You need to understand how autowiring, or in fact Java in general, works.
Spring must create an instance of your ServImpl class, and populate the field repo with the repository bean. It does that using reflection, but what it does is basically equivalent to the following code:
ServImpl s = new ServImpl();
s.repo = theRepoBean;
So, you see that s.repo becomes non-null after the constructor has been executed. And, while executing the constructor, the following line of code is executed:
List<Student> s = repo.getAllSiswa();
At that moment, repo hasn't been initialized yet. So it's null. So you get a NullPointerException.
Use constructor injection instead of field injection, or use a #PostConstruct annotated method.
And please, make your fields private instead of public.
That said, the goal of a repository is normally to get data from a database. And the students can be modified,deleted or created in the database. So initializing a field of your service and returning always the same list defeats the whole point of having a repo. You should call repo.getAllSiswa() from newList(), every time it's called, to get the latest, up-to-date, list of students.
Because Autowired on field happens right after construction, you need to change your code in order to get it to work.
This should works:
#Service
public class ServeImplement implements Serve {
public Repo repo;
List<Student> s;
#Autowired
public ServeImplement(Repo repo) {
this.repo = repo;
s = repo.getAllSiswa();
}
#Override
public void changeName(String namaBaru) {
s.get(0).setNama(namaBaru); // get first Student, then update its name.
}
#Override
public List<Student> newList() {
return this.s;
}
}
Moreover, using Autorwired annotation on constructor allow you to mark your field as final if the instance shouldn't have to change.
Related
I am working on spring boot app with tutorial. I did everything like guy from tutorial but still have problem with some constructor:(
The error is:
Parameter 0 of constructor in com.wewtorek.shop.controllers.AdminController required a bean of type 'com.wewtorek.shop.models.data.PageRepository' that could not be found.
Code is:
package com.wewtorek.shop.controllers;
import com.wewtorek.shop.models.data.Page;
import com.wewtorek.shop.models.data.PageRepository;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.List;
#Controller
#RequestMapping("/admin")
public class AdminController {
private PageRepository pageRepository;
public AdminController(PageRepository pageRepository) {
this.pageRepository = pageRepository;
}
#GetMapping
public String admin(Model model) {
List<Page> pages = pageRepository.findAll();
model.addAttribute("pages", pages);
return "admin";
}
}
PageRepository:
package com.wewtorek.shop.models.data;
import org.springframework.data.jpa.repository.JpaRepository;
public interface PageRepository extends JpaRepository<Page, Integer> {
}
Application:
package com.wewtorek.shop;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ShopApplication {
public static void main(String[] args) {
SpringApplication.run(ShopApplication.class, args);
}
}
First :
#Repository is missing
#Repository
public interface PageRepository extends JpaRepository<Page, Integer> {
}
Doc : https://www.baeldung.com/spring-data-repositories
You dont have to create an constructor in controller :
It should be something like this :
public class AdminController{
#Autowired
private PageRepository pageRepository;
--- Code ---
}
#Autowired instanciate a service, you dont have to build it
BUT you have to put #Repository or #Service to use #Autowired
I take this example from my school project :
Controller
In my LoanService i call another server but u can replace it by u'r repository
Service
And last tips i promise :D, a complete NoSQL school project i did
https://github.com/juju630/ClientServeurNoSQL
( sry not native )
Without looking at your project, this is going to be hard to give a definitive solution.
What is happening is when spring tries to create the bean AdminController it can not find a unique bean as the dependency PageRepository.
A few things to look at to try to solve this
Is the bean JpaRepository<Page, Integer> annotated correctly for spring to pick it up and create an instance?
Is the bean JpaRepository<Page, Integer> being scanned by spring?
What is your package structure? this can be very important for the default scanning of spring beans.
To investigate you could add a default constructor to allow it to ignore the dependency, then debug out all beans on startup of your app using the answers
Here
I hope this helps.
I created a new class with below piece of logic.
import com.google.cloud.bigtable.data.v2.stub.EnhancedBigtableStubSettings;
import com.google.protobuf.ByteString;
import java.util.List;
import java.util.logging.Logger;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.threeten.bp.Duration;
#Component
#RefreshScope
public class PrimeChannel {
private final EnhancedBigtableStubSettings enhancedBigtableStubSettings;
private final List<String> tableIds;
public PrimeChannel(EnhancedBigtableStubSettings enhancedBigtableStubSettings, List<String> tableIds) {
this.enhancedBigtableStubSettings = enhancedBigtableStubSettings;
this.tableIds = tableIds;
}
}
While running i am getting below error
Parameter 0 of constructor in myPackage.PrimeChannel required a bean of type 'com.google.cloud.bigtable.data.v2.stub.EnhancedBigtableStubSettings' that could not be found.
Action:
Consider defining a bean of type 'com.google.cloud.bigtable.data.v2.stub.EnhancedBigtableStubSettings' in your configuration.
I am passing EnhancedBigtableStubSettings object as first parameter then why its not considering.
if i try with 0 argument constructor by initializing EnhancedBigtableStubSettings as null will throws null pointer exception in later stages.
How can deal with this?
Can anyone help on this?
At first, you must create a bean of EnhancedBigtableStubSettings class. You can define it in applicationContext.xml or #Configuration class, then annotate the constructor with #Autowired.
<bean name="beanName" class="foo.EnhancedBigtableStubSettings"/>
#Bean(name = "beanName")
public EnhancedBigtableStubSettings getEnhancedBigtableStubSettings() {
//return object somehow
return new EnhancedBigtableStubSettings();
}
so I'm working on an API Rest, registration for students, using Domain Driven Design. So my problem is: I'm trying to add a custom method with the JpaRepository. My Project hierarchy is:
com.wizardry.witchcraft.domain.model.StudentModel;
com.wizardry.witchcraft.infraestructure.repository.CustomRepositoryImpl;
com.wizardry.witchcraft.domain.repository.IStudentRepository;
com.wizardry.witchcraft.domain.repository.ICustomRepository;
com.wizardry.witchcraft.api.controller.TesteController2;
com.wizardry.witchcraft.api.controller.StudentController;
So first I've created the method Implementation
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import com.wizardry.witchcraft.domain.model.StudentModel;
import com.wizardry.witchcraft.domain.repository.ICustomRepository;
#Repository
public class CustomRepositoryImpl implements ICustomRepository {
#PersistenceContext
private EntityManager manager;
#Override
public List<StudentModel> findCustom (String name){
//METHOD
}
}
And the Interface:
import com.wizardry.witchcraft.domain.model.StudentModel;
public interface ICustomRepository {
List<StudentModel> findCustom(String name);
}
And to test it out I created a new Controller to don't mess with my working one, TesteController2, and it worked fine. So my next step was extended the ICustomRepository in the IStudentRepository, made the changes in TesteController2 and then Spring won't find my findCustom method anymore, It tries to create the method as a JPA keyword and return and error. This is my repository interface:
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import com.wizardry.witchcraft.domain.model.StudentModel;
#Repository
public interface IStudentRepository extends ICustomRepository, JpaRepository<StudentModel, Long> {
List<StudentModel> queryByName(String name, #Param ("id") Long school);
List<StudentModel> queryFirstByNameContaining(String name);
List<StudentModel> queryTop2ByNameContaining(String name);
int countByWizardingSchoolModelId(Long school);
}
And the TesteController2:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import com.wizardry.witchcraft.domain.model.StudentModel;
import com.wizardry.witchcraft.domain.repository.IStudentRepository;
#RestController
#RequestMapping(value = "/test")
public class TesteController2 {
#Autowired
private IStudentRepository iStudentRepository;
#ResponseStatus(HttpStatus.ACCEPTED)
#GetMapping
public List<StudentModel> findCustom2(String name) {
return iStudentRepository.findCustom(name);
}
}
PS: I have a Service Layer com.wizardry.witchcraft.domain.service.RegisterStudentService however
the method in question does not go through it(yet!) because I'm testing, I tried to pass by the service and see what happen but give the same ERROR.
*
ERROR: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'studentController': Unsatisfied dependency expressed through field 'registerStudentService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'registerStudentService': Unsatisfied dependency expressed through field 'iStudentRepository'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'IStudentRepository' defined in com.wizardry.witchcraft.domain.repository.IStudentRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Invocation of init method failed; nested exception is java.lang.IllegalArgumentException: Failed to create query for method public abstract java.util.List com.wizardry.witchcraft.domain.repository.ICustomRepository.findCustom(java.lang.String)! No property findCustom found for type StudentModel!
*
Thanks in Advance! I'm really lost here.
Just rename your class CustomRepositoryImpl to IStudentRepositoryImpl and it should work.
#Repository
public class IStudentRepositoryImpl implements ICustomRepository {
#PersistenceContext
private EntityManager manager;
#Override
public List<StudentModel> findCustom (String name){
//METHOD
}
}
Below is the documentation from Spring
Configuration If you use namespace configuration, the repository
infrastructure tries to autodetect custom implementations by scanning
for classes below the package we found a repository in. These classes
need to follow the naming convention of appending the namespace
element's attribute repository-impl-postfix to the found repository
interface name. This postfix defaults to Impl.
https://docs.spring.io/spring-data/data-commons/docs/current-SNAPSHOT/reference/html/#repositories.custom-implementations
I'm getting the following error when trying to run my app:
Field edao in com.alon.service.EmployeeServiceImpl required a bean of
type 'com.alon.repository.EmployeeRepository' that could not be found.
The injection point has the following annotations:
#org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type
'com.alon.repository.EmployeeRepository' in your configuration.
Project structure:
EmployeeRepository:
package com.alon.repository;
import com.alon.model.Employee;
import org.springframework.stereotype.Repository;
import java.util.List;
#Repository
public interface EmployeeRepository {
List<Employee> findByDesignation(String designation);
void saveAll(List<Employee> employees);
Iterable<Employee> findAll();
}
EmployeeServiceImpl:
package com.alon.service;
import com.alon.model.Employee;
import com.alon.repository.EmployeeRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class EmployeeServiceImpl implements EmployeeService {
#Autowired
private EmployeeRepository edao;
#Override
public void saveEmployee(List<Employee> employees) {
edao.saveAll(employees);
}
#Override
public Iterable<Employee> findAllEmployees() {
return edao.findAll();
}
#Override
public List<Employee> findByDesignation(String designation) {
return edao.findByDesignation(designation);
}
}
MyApplication:
package com.alon;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class MyApplicataion {
public static void main(String[] args) {
SpringApplication.run(MyApplicataion.class, args);
}
}
As you have added spring-boot tag I guess you are using sprig data jpa. Your repository interfaces should extend org.springframework.data.repository.Repository (a marker interface) or one of its sub interfaces (usually org.springframework.data.repository.CrudRepository) for instructing spring to provide a runtime implementation of your repository, if any of those interfaces are not extened you'll get
bean of type 'com.alon.repository.EmployeeRepository' that could not
be found.
I assume you try to use spring data JPA. What you can check / debug is:
Is JpaRepositoriesAutoConfiguration executed? You can see this in the start up log in the debug log level
Does something change if you addionally add #EnableJpaRepositories with the corresponding basepackages.
Add #ComponentScan with the corresponding packages, normally #SpringBootApplication should do it, but just in case.
you can also check the autconfig documentation: https://docs.spring.io/spring-boot/docs/current/reference/html/using-boot-auto-configuration.html
EDIT: see comment from #ali4j: I did not see that it is the generic spring Repository interface and not the spring data interface
regards,WiPu
I wanted to play around with the different types of bean scopes. So I wrote a test environment which should generate a random number so I could see if a bean had changed. My test setup does not work and I can not explain what I found out.
I'm using Spring Boot 2.13 with the Spring Framework 5.15.
Following setup:
Main class:
package domain.webcreator;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class WebcreatorApplication {
public static void main(String[] args) {
SpringApplication.run(WebcreatorApplication.class, args);
}
}
Beans class:
package domain.webcreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.util.Random;
#Configuration
public class Beans {
#Bean
public Random randomGenerator() {
return new Random();
}
}
Scoper class:
package domain.webcreator;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;
import java.util.Random;
#Service
#Scope("singleton")
public class Scoper {
private Random rand;
public Scoper(Random rand) {
this.rand = rand;
}
public int getNumber(int max) {
return rand.nextInt(max);
}
}
Index Controller
package domain.webcreator.controller;
import domain.webcreator.Scoper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
#Controller
public class IndexController {
#GetMapping("/")
#ResponseBody
#Autowired
public String indexAction(Scoper scoper) {
return String.valueOf(scoper.getNumber(50));
}
}
My problem is, that I get an NPE while calling scoper.getNumber(50).
This is strange because when debugging, a Random bean is generated and passed to the scoper constructor.
Later on, in the controller, the rand property is null.
What am I doing wrong?
You're trying to apply #Autowired to a random method, which isn't how Spring works. Controller method parameters are for information specific to that HTTP request, not general dependencies, and so Spring is trying to create a new Scoper that is associated with the request--but it doesn't have any incoming values in the request to fill in. (I'm actually surprised you're not getting an error about no default constructor.)
Instead, pass your Scoper in a constructor.
#RestController
public class IndexController {
private final Scoper scoper;
public IndexController(Scoper scoper) {
this.scoper = scoper;
}
#GetMapping("/")
public String indexAction(Scoper scoper) {
return String.valueOf(scoper.getNumber(50));
}
}
A couple of notes:
Singleton scope is the default, and there's no need to specify it.
#RestController is preferable to repeating #ResponseBody unless you have a mixed controller class.