mockit.internal.MissingInvocation Exception - using Spring , Jmockit - spring

I am using JMockit with Spring and trying to verify some method from my service layer but i couldn't make it successful.
Find the below sample code
UserRepositoryImpl.java
package com.test.jmockit.JMockitsample.repository.impl;
import org.springframework.stereotype.Repository;
import com.test.jmockit.JMockitsample.User;
import com.test.jmockit.JMockitsample.repository.UserRepository;
#Repository("userRepository")
public class UserRepositoryImpl implements UserRepository{
/**
* Not yet implemented.
*
* #param User
* #return
*/
public User getLoggedInUser() {
User user = new User();
user.setUsername("admin");
user.setPassword("test123");
return user;
}
}
UserServiceImpl.java
/**
*
*/
package com.test.jmockit.JMockitsample.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.test.jmockit.JMockitsample.User;
import com.test.jmockit.JMockitsample.repository.UserRepository;
import com.test.jmockit.JMockitsample.service.UserService;
#Service("userService")
public class UserServiceImpl implements UserService{
#Autowired
private UserRepository userRepository;
public User getLoggedInUser() {
// TODO Auto-generated method stub
User user = userRepository.getLoggedInUser();
System.out.println("user service " + user.getUsername());
return user;
}
}
And my Test class
#ContextConfiguration(locations = { "classpath:/ApplicationContext.xml" })
#RunWith(SpringJUnit4ClassRunner.class)
public class JMockitVerificationTest {
#Tested
private UserService userService = new UserServiceImpl();
#Injectable
private UserRepository userRepository;
#Test
public void testUserServiceUserList() {
new Expectations() {
{
userRepository.getLoggedInUser();
result = new User("guest", "test123");
}
};
userService.getLoggedInUser();
new Verifications() {
{
userRepository.getLoggedInUser();
}
};
}
}
It's running success if i remove the verification block and getting expected result.
Trying to verify my method whether it is get invoked in service or not but getting below exception.
mockit.internal.MissingInvocation: Missing invocation of:
com.test.jmockit.JMockitsample.repository.UserRepository#getLoggedInUser()
on mock instance: com.test.jmockit.JMockitsample.repository.$Impl_UserRepository#425407
at com.test.jmockit.JMockitVerificationTest$2.<init>(JMockitVerificationTest.java:45)
at com.test.jmockit.JMockitVerificationTest.testUserServiceUserList(JMockitVerificationTest.java:42)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.apache.maven.surefire.junit4.JUnit4Provider.execute(JUnit4Provider.java:242)
at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:137)
at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:112)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.apache.maven.surefire.util.ReflectionUtils.invokeMethodWithArray(ReflectionUtils.java:189)
at org.apache.maven.surefire.booter.ProviderFactory$ProviderProxy.invoke(ProviderFactory.java:165)
at org.apache.maven.surefire.booter.ProviderFactory.invokeProvider(ProviderFactory.java:85)
at org.apache.maven.surefire.booter.ForkedBooter.runSuitesInProcess(ForkedBooter.java:115)
at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:75)
Caused by: Missing invocation
... 24 more
Don't know where i have done the mistake to make it success, thanks in advance.

Related

Mock test for Login Controller throwing null pointer exception for AuthenticationManager

I have an error when I try to create a post request in my Mock test. It tells me that the authenticationManager is null(meaning it wasn't autowired).
I have a Login Controller having an autowired AuthenticationManager with three methods(login/register/userinfo) .
I tried to create a Login Controller Test with an instance of LoginController having injectedMocks but I don't know how to use it(I am not accustomed to testing).
Login Controller
#RestController
#RequestMapping("/auth")
#CrossOrigin
public class LoginController {
#Autowired
private AuthenticationManager authenticationManager;
#Autowired
JWTTokenHelper jWTTokenHelper;
#Qualifier("myUserDetails")
#Autowired
private UserDetailsService userDetailsService;
String jwtToken;
private final UserService userService;
#Autowired
LoginController(UserService userService){
this.userService = userService;
}
#PostMapping(value = "/register",consumes = "application/json")
public ResponseEntity<?> register(#RequestBody RegistrationDTO registrationDTO) throws InvalidKeySpecException, NoSuchAlgorithmException {
return this.login(new AuthenticationDTO(registrationDTO.getEmail(), registrationDTO.getPassword()));
}
#PostMapping(value = "/login",consumes = "application/json")
public ResponseEntity<?> login(#RequestBody AuthenticationDTO authenticationDTO) throws InvalidKeySpecException, NoSuchAlgorithmException {
System.out.print("\n" + authenticationDTO.getEmail() + " " + authenticationDTO.getPassword() + "\n");
final Authentication authentication = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken(
authenticationDTO.getEmail(), authenticationDTO.getPassword()));
SecurityContextHolder.getContext().setAuthentication(authentication);
UserDetails userDetails=(UserDetails) authentication.getPrincipal();
String jwtToken=jWTTokenHelper.generateToken(userDetails.getUsername());
this.jwtToken = jwtToken;
LoginResponseDTO responseDTO = new LoginResponseDTO(jwtToken);
//try to find out if it's a customer or not
return ResponseEntity.ok(responseDTO);
}
#GetMapping("/userinfo")
#ResponseBody
public ResponseEntity<?> getUserInfo(Principal user){
User userObj = (User)userDetailsService.loadUserByUsername(user.getName());
UserDTO userInfo = new UserDTO(userObj.getId(),userObj.getName(),userObj.getEmail(),userObj.getAuthorities().toArray());
return ResponseEntity.ok(userInfo);
}
}
Login Controller Test
import com.example.demo.Controller.LoginController;
import com.example.demo.Model.DTOs.AuthenticationDTO;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.junit.MockitoJUnitRunner;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.http.MediaType;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
#AutoConfigureMockMvc
#RunWith(MockitoJUnitRunner.class)
public class LoginControllerTest {
#Autowired
private MockMvc mockMvc;
#InjectMocks
private LoginController loginController;
#Before
public void setUp(){
mockMvc = MockMvcBuilders.standaloneSetup(loginController).build();
}
#Test
public void testLogin() throws Exception{
AuthenticationDTO authenticationDTO = new AuthenticationDTO("ztudorita#gmail.com","Shaorma72.");
mockMvc.perform(
MockMvcRequestBuilders
.post("/auth/login")
.contentType(MediaType.APPLICATION_JSON)
.content(asJsonString(authenticationDTO))
// .accept(MediaType.APPLICATION_JSON)
)
.andReturn();
}
public static String asJsonString(final Object obj) {
try {
return new ObjectMapper().writeValueAsString(obj);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
ERROR CONSOLE
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1014)
at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:909)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:681)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:72)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:764)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:199)
at com.example.demo.ControllerTest.LoginControllerTest.testLogin(LoginControllerTest.java:38)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:55)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:100)
at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:107)
at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:41)
at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:69)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:220)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:53)
Caused by: java.lang.NullPointerException
at com.example.demo.Controller.LoginController.login(LoginController.java:59)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at

MockMvc peform is return nullPointerException in integration tests

I'm trying to run integration tests for my Spring project, it's a simple get method that returns a String output from the DB for the id given. But I keep getting a NullPointerException on the Mockmvc in the MockMvc.perform within my tests.
Here is the test:
#WebMvcTest(OutputController.class)
public class OutputControllerTests {
#Autowired
private MockMvc mockMvc;
#MockBea
OutputService outputService;
#Test
public void returnOutputForValidId() throws Exception {
OutputService service = Mockito.mock(OutputService.class);
when(service.findOutputById("TEST")).thenReturn("Test output");
String getOutputMapping = "/output/{systemID}";
String id = "TEST";
mockMvc.perform(get(getOuputMapping, id))
.andDo(print()).andExpect(status().isOk())
.andExpect(content().string("Test output"));
}
Here is the controller - OutputController:
#RestController
public class OutputController {
private final OutputService outputService;
public OutputController(OutputService outputService) {
this.outputService = outputService;
}
#GetMapping("/output/{id}")
#CrossOrigin
public String getOutputByID(#PathVariable String Id) {
String output = outputService.findOutputById(Id);
return output;
}
}
The full error is :
java.lang.NullPointerException
at .com.output.OutputControllerTests.returnOutputForValidId(OutputControllerTests.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:366)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:331)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:79)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:329)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:66)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:293)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:306)
at org.junit.runners.ParentRunner.run(ParentRunner.java:413)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
You don't need to autowire MockMvc object. Try with this instead:
import org.junit.jupiter.api.BeforeEach;
//...
private MockMvc mockMvc;
//...
#BeforeEach
public void setUp(WebApplicationContext context) {
mockMvc = MockMvcBuilders.webAppContextSetup(context).build();
}

NullPointerException in the BeforeClass (spring boot)

I want to make an insert in my DB before all tests just once. That's what I'm trying to do in the setUp() method. But got nullpointer. Spring boot version is 1.5.1.RELEASE. Any ideas?
This is from my test class:
#Autowired
private static UserRepository userRepository;
#BeforeClass
public static void setUp() {
User user = User.
.builder()
.id(10)
.name("John")
.build();
userRepository.deleteAll(); //NullPointerException at this step
userRepository.save(user);
}
This is my entity class:
#Entity
#Table(schema="test", name = "TBL_USERS")
#AllArgsConstructor
#Builder
#Data public class User implements Persistable<String>{
#Id
#Column(name = "ID", columnDefinition = "decimal")
private String id;
#Column(name = "NAME", columnDefinition = "char", nullable = false)
private String name;
...
}
This is the interface:
public interface UserRepository extends JpaRepository<User, String> {}
The stack trace:
java.lang.NullPointerException
at com.company.myapp.get.GetUserTest.setUp(GetUserTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Short answer: You can not inject static UserRepository (#Autowired)
Please read here Reason we could not inject static field
It doesn't look like you initialized userRepository to anything in your beforeClass method before calling deleteAll() on it. That's why you got your NPE.
Is your test class annotated with #RunWith(SpringRunner.class)?
You need to do something like this..
#RunWith(SpringRunner.class)
#SpringBootTest
public class XXXTest {
#Autowired
private UserRepository userRepository;
#Before
public void setUp() {
......
}

Testing Spring Boot REST json result

I have some problem with checking json result
UserControllerTest class
package com.serwis.controller;
import com.serwis.PraktykiApplication;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.hamcrest.Matchers;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.SpringApplicationConfiguration;
import org.springframework.boot.test.TestRestTemplate;
import org.springframework.boot.test.WebIntegrationTest;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.client.RestTemplate;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.standaloneSetup;
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(PraktykiApplication.class)
#WebIntegrationTest
public class UserControllerTests {
#Autowired
private UserRepository userRepository;
User user;
private MockMvc mockMvc;
#Before
public void setUp(){
user = new User("login1","password","email");
userRepository.deleteAll();
userRepository.save(user);
this.mockMvc = standaloneSetup(new UserController()).build();
}
#Test
public void createUser() throws Exception {
this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$.login", is("login1")));
System.out.println(userRepository.findAll());
}
}
User class
package com.serwis.model;
import javax.persistence.*;
import java.util.Arrays;
import java.util.Set;
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="id")
private long id;
#Column(name="login")
private String login;
#Column(name="password")
private String password;
#Column(name="email")
private String email;
#Column(name="avatar")
private byte[] avatar;
public User(){}
public User(String login, String password, String email) {
this.login = login;
this.password = password;
this.email = email;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", login='" + login + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", avatar=" + Arrays.toString(avatar) +
'}';
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public byte[] getAvatar() {
return avatar;
}
public void setAvatar(byte[] avatar) {
this.avatar = avatar;
}
}
UserRepository class
package com.serwis.repository;
import com.serwis.model.User;
import org.springframework.data.repository.CrudRepository;
import org.springframework.transaction.annotation.Transactional;
#Transactional
public interface UserRepository extends CrudRepository<User, Long>{
}
userController class
package com.serwis.controller;
import com.serwis.model.User;
import com.serwis.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Created by Jodanpotasu on 2016-07-24.
*/
#Controller
public class UserController {
#Autowired
private UserRepository userRepository;
#RequestMapping("/user/create")
#ResponseBody
public String create(String email, String login, String password) {
String userId = "";
try {
User user = new User(email, login, password);
userRepository.save(user);
userId = String.valueOf(user.getId());
} catch (Exception ex) {
return "Error creating the user: " + ex.toString();
}
return "User succesfully created with id = " + userId;
}
#RequestMapping("/user/findall/")
#ResponseBody
public Iterable<User> findAll() {
return userRepository.findAll();
}
#RequestMapping("/user/delete")
#ResponseBody
public String delete(long id) {
User deleted = userRepository.findOne(id);
userRepository.delete(id);
return "USER DELETED: " + deleted;
}
#RequestMapping("/user/update")
#ResponseBody
public String update(long id, String login, String password, String email) {
User beforeUpdate = userRepository.findOne(id);
User afterUpdate = userRepository.findOne(id);
afterUpdate.setLogin(login);
afterUpdate.setEmail(email);
afterUpdate.setPassword(password);
return "BEFORE UPDATE: \n" + beforeUpdate + " <br> AFTER UPDATE: " + afterUpdate;
}
}
it should be like
[{"id":1,"login":"login1","password":"password","email":"email","avatar":null}]
But i still have error output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
and that is full output
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.NullPointerException
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:979)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:858)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:843)
at org.springframework.test.web.servlet.TestDispatcherServlet.service(TestDispatcherServlet.java:65)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.springframework.mock.web.MockFilterChain$ServletFilterProxy.doFilter(MockFilterChain.java:167)
at org.springframework.mock.web.MockFilterChain.doFilter(MockFilterChain.java:134)
at org.springframework.test.web.servlet.MockMvc.perform(MockMvc.java:155)
at com.serwis.controller.UserControllerTests.createUser(UserControllerTests.java:56)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:254)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:89)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:193)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:253)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
at com.serwis.controller.UserController.findAll(UserController.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:221)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:110)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:832)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:743)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:961)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:895)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:967)
... 43 more
Spring boot version: 1.3.6 is there another better way to test json?
Here is my working class
#RunWith(SpringJUnit4ClassRunner.class)
#SpringApplicationConfiguration(PraktykiApplication.class)
#WebIntegrationTest
public class UserControllerTests {
#Autowired
private UserRepository userRepository;
User user;
private MockMvc mockMvc;
#Autowired
UserController userController;
#Before
public void setUp(){
user = new User("login1","password","email");
userRepository.deleteAll();
userRepository.save(user);
this.mockMvc = standaloneSetup(userController).build();
}
#Test
public void createUser() throws Exception {
this.mockMvc.perform(get("/user/findall/").accept(MediaType.parseMediaType("application/json;charset=UTF-8")))
.andExpect(status().isOk())
.andExpect(content().contentType("application/json;charset=UTF-8"))
.andExpect(jsonPath("$[0].login", is("login1")));
System.out.println(userRepository.findAll());
}
}
it seems that spring boot did not see
this.mockMvc = standaloneSetup(new UserController()).build();

java.lang.NullPointerException upon EntityManager injection in Spring repository

I am new to Spring MVC. I've been searching for few days for a solution to my problem, without any success.
Here is my stack:
jBoss 4.2.3GA server
I know it's a very old version, but that is what I am limited to right now. jBoss 7.1 will be approved for use in my organization within the next few months, but I would like to make my R&D application work in the 4.2.3GA server. That means I have added all required jars in my /lib folder.
Spring MVC 4.0.2
EJB3.0 / JPA for persistence
DBMS is PostgreSQL 9.0.3
I am not using any build/dependency management tool such like Maven or Gradle. Gradle is in approval process so it's a matter of time. I need to manage all dependencies myself for now.
My project structure:
src
baseproject
model
security
User.java
Role.java
... other security related entity beans
repository
security
UserRepository.java
UserRepositoryImpl.java
RoleRepository.java
RoleRepositoryImpl.java
... other security related repositories
service
SecurityService.java
SecurityServiceImpl.java
web
controller
UserController.java (a typical controller)
configuration
WebConfig.java (the main servlet configuration)
PersistenceConfig.java (everything related to persistence. I think this is where my problem is... no persistence.xml)
PersistenceConfig.java
package baseproject.web.configuration;
import java.util.Properties;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.lookup.JndiDataSourceLookup;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.orm.jpa.vendor.Database;
import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class PersistenceConfig {
#Bean
public EntityManagerFactory entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean localContainerEntityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
localContainerEntityManagerFactoryBean.setJpaVendorAdapter(jpaVendorAdapter());
localContainerEntityManagerFactoryBean.setDataSource(dataSource());
localContainerEntityManagerFactoryBean.setPackagesToScan("baseproject");
final Properties props = new Properties();
props.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
props.setProperty("hibernate.hbm2ddl.auto", "validate");
props.setProperty("hibernate.show_sql", "false");
props.setProperty("hibernate.validator.apply_to_ddl", "false");
props.setProperty("hibernate.validator.autoregister_listeners", "false");
localContainerEntityManagerFactoryBean.setJpaProperties(props);
return localContainerEntityManagerFactoryBean.getObject();
}
#Bean
public HibernateJpaVendorAdapter jpaVendorAdapter() {
HibernateJpaVendorAdapter hibernateJpaVendorAdapter = new HibernateJpaVendorAdapter();
hibernateJpaVendorAdapter.setDatabase(Database.POSTGRESQL);
hibernateJpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.PostgreSQLDialect");
return hibernateJpaVendorAdapter;
}
#Bean
public DataSource dataSource() {
final JndiDataSourceLookup dsLookup = new JndiDataSourceLookup();
dsLookup.setResourceRef(true);
DataSource dataSource = dsLookup.getDataSource("java:/dsBaseProject");
return dataSource;
}
}
UserRepository.java
package baseproject.repository.security;
import java.util.List;
import baseproject.model.security.User;
public interface UserRepository {
public User findUserByPk(Integer intUserId);
public List<User> lstUsers(Integer intSortBy);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
}
UserRepositoryImpl.java
package baseproject.repository.security;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import org.springframework.stereotype.Repository;
import baseproject.model.security.User;
#Repository
public class UserRepositoryImpl implements UserRepository {
#PersistenceContext
protected EntityManager em;
public User findUserByPk(Integer intId) {
User user = null;
if (intId != null) {
user = em.find(User.class, intId);
}
return user;
}
public java.util.List<User> lstUsers(Integer intSortBy) {
List<User> usersList = new ArrayList<User>();
Query q = em.createNamedQuery("User.lstUsers");
return usersList;
}
public void addUser(User user) {
user.setIntId(null);
em.persist(user);
}
public void updateUser(User user) {
User userBd = em.find(User.class, user.getIntId());
userBd.setStrLastName(user.getStrLastName());
userBd.setStrFirstName(user.getStrFirstName());
userBd.setStrUserId(user.getStrUserId());
}
public void deleteUser(User user) {
User userBd = em.find(User.class, user.getIntId());
em.remove(userBd);
}
}
SecurityService.java
package baseproject.service;
import java.util.List;
import baseproject.model.security.Method;
import baseproject.model.security.Node;
import baseproject.model.security.Role;
import baseproject.model.security.User;
public interface SecurityService {
// USERS
public User findUserByPk(Integer intUserId);
public User findUserByUserId(String strUserId);
public void addUser(User user);
public void updateUser(User user);
public void deleteUser(User user);
public List<User> lstUsers(Integer intSortBy);
public boolean validateUser(User user, String strMethod);
// ROLES
public Role findRoleByPk(Integer intRoleId);
public List<Role> lstRoles(String strLanguage);
public void addRole(Role role);
public void updRole(Role role);
public void delRole(Role role);
// NODES
public List<Node> lstParentNodes();
// METHODS
public Method findMethodByPk(Integer intMethodId);
public Method findMethodByName(String strName);
public List<String> lstUserAllowedMethods(List<Role> lstRolesAllowed, String strLang, String strRemoteUser);
public List<Method> lstAllMethods();
}
SecurityServiceImpl.java
package baseproject.service;
import java.util.List;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import baseproject.model.security.Method;
import baseproject.model.security.Node;
import baseproject.model.security.Role;
import baseproject.model.security.User;
import baseproject.repository.security.MethodRepository;
import baseproject.repository.security.NodeRepository;
import baseproject.repository.security.RoleRepository;
import baseproject.repository.security.UserRepository;
#Service
public class SecurityServiceImpl implements SecurityService {
UserRepository userRepository;
RoleRepository roleRepository;
MethodRepository methodRepository;
NodeRepository nodeRepository;
#Override
#Transactional(readOnly = true)
public User findUserByPk(Integer intUserId) {
return userRepository.findUserByPk(intUserId);
}
#Override
#Transactional(readOnly = true)
public User findUserByUserId(String strUserId) {
return userRepository.findUserByUserId(strUserId);
}
#Override
#Transactional
public void addUser(User user) {
userRepository.addUser(user);
}
#Override
#Transactional
public void updateUser(User user) {
userRepository.updateUser(user);
}
#Override
#Transactional
public void deleteUser(User user) {
userRepository.deleteUser(user);
}
#Override
#Transactional(readOnly = true)
public List<User> lstUsers(Integer intSortBy) {
return null;
}
#Override
#Transactional(readOnly = true)
public boolean validateUser(User user, String strMethod) {
return false;
}
#Override
#Transactional(readOnly = true)
public Role findRoleByPk(Integer intRoleId) {
return null;
}
#Override
#Transactional(readOnly = true)
public List<Role> lstRoles(String strLanguage) {
return roleRepository.lstRoles(strLanguage);
}
#Override
#Transactional
public void addRole(Role role) {
roleRepository.addRole(role);
}
#Override
#Transactional
public void updRole(Role role) {
}
#Override
#Transactional
public void delRole(Role role) {
}
#Override
#Transactional
public List<Node> lstParentNodes() {
return nodeRepository.lstParentNodes();
}
#Override
#Transactional
public Method findMethodByPk(Integer intMethodId) {
return methodRepository.findMethodByPk(intMethodId);
}
#Override
#Transactional
public Method findMethodByName(String strName) {
return methodRepository.findMethodByName(strName);
}
#Override
#Transactional
public List<String> lstUserAllowedMethods(List<Role> arlRolesAllowed,
String strLanguage, String strRemoteUser) {
return methodRepository.lstUserAllowedMethods(arlRolesAllowed, strLanguage, strRemoteUser);
}
#Override
#Transactional
public List<Method> lstAllMethods() {
return methodRepository.lstAllMethods();
}
}
I have based my structure on the Spring petclinic application, which uses the repository-service design pattern. The problem is occuring upon deployment. I got the following stacktrace right when the first Spring repository is getting processed because of the #Repository annotation:
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepositoryImpl': Injection of persistence dependencies failed; nested exception is java.lang.NullPointerException
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:356)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1185)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:537)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:475)
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:304)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:300)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:195)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:700)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:760)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:482)
at org.springframework.web.context.ContextLoader.configureAndRefreshWebApplicationContext(ContextLoader.java:403)
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:306)
at org.springframework.web.context.ContextLoaderListener.contextInitialized(ContextLoaderListener.java:106)
at org.apache.catalina.core.StandardContext.listenerStart(StandardContext.java:3856)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4361)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:790)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:770)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:553)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.apache.catalina.core.StandardContext.init(StandardContext.java:5312)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.apache.tomcat.util.modeler.BaseModelMBean.invoke(BaseModelMBean.java:296)
at org.jboss.mx.server.RawDynamicInvoker.invoke(RawDynamicInvoker.java:164)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.web.tomcat.service.TomcatDeployer.performDeployInternal(TomcatDeployer.java:301)
at org.jboss.web.tomcat.service.TomcatDeployer.performDeploy(TomcatDeployer.java:104)
at org.jboss.web.AbstractWebDeployer.start(AbstractWebDeployer.java:375)
at org.jboss.web.WebModule.startModule(WebModule.java:83)
at org.jboss.web.WebModule.startService(WebModule.java:61)
at org.jboss.system.ServiceMBeanSupport.jbossInternalStart(ServiceMBeanSupport.java:289)
at org.jboss.system.ServiceMBeanSupport.jbossInternalLifecycle(ServiceMBeanSupport.java:245)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.system.ServiceController$ServiceProxy.invoke(ServiceController.java:978)
at $Proxy0.start(Unknown Source)
at org.jboss.system.ServiceController.start(ServiceController.java:417)
at sun.reflect.GeneratedMethodAccessor9.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:86)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy42.start(Unknown Source)
at org.jboss.web.AbstractWebContainer.start(AbstractWebContainer.java:466)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.interceptor.DynamicInterceptor.invoke(DynamicInterceptor.java:97)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy43.start(Unknown Source)
at org.jboss.deployment.MainDeployer.start(MainDeployer.java:1025)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:819)
at org.jboss.deployment.MainDeployer.deploy(MainDeployer.java:782)
at sun.reflect.GeneratedMethodAccessor46.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at org.jboss.mx.interceptor.ReflectedDispatcher.invoke(ReflectedDispatcher.java:155)
at org.jboss.mx.server.Invocation.dispatch(Invocation.java:94)
at org.jboss.mx.interceptor.AbstractInterceptor.invoke(AbstractInterceptor.java:133)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.interceptor.ModelMBeanOperationInterceptor.invoke(ModelMBeanOperationInterceptor.java:142)
at org.jboss.mx.server.Invocation.invoke(Invocation.java:88)
at org.jboss.mx.server.AbstractMBeanInvoker.invoke(AbstractMBeanInvoker.java:264)
at org.jboss.mx.server.MBeanServerImpl.invoke(MBeanServerImpl.java:659)
at org.jboss.mx.util.MBeanProxyExt.invoke(MBeanProxyExt.java:210)
at $Proxy9.deploy(Unknown Source)
at org.jboss.deployment.scanner.URLDeploymentScanner.deploy(URLDeploymentScanner.java:421)
at org.jboss.deployment.scanner.URLDeploymentScanner.scan(URLDeploymentScanner.java:610)
at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.doScan(AbstractDeploymentScanner.java:263)
at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.loop(AbstractDeploymentScanner.java:274)
at org.jboss.deployment.scanner.AbstractDeploymentScanner$ScannerThread.run(AbstractDeploymentScanner.java:225)
Caused by: java.lang.NullPointerException
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.initProxyClassLoader(SharedEntityManagerCreator.java:171)
at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.<init>(SharedEntityManagerCreator.java:163)
at org.springframework.orm.jpa.SharedEntityManagerCreator.createSharedEntityManager(SharedEntityManagerCreator.java:135)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.resolveEntityManager(PersistenceAnnotationBeanPostProcessor.java:694)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor$PersistenceElement.getResourceToInject(PersistenceAnnotationBeanPostProcessor.java:655)
at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:155)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87)
at org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor.postProcessPropertyValues(PersistenceAnnotationBeanPostProcessor.java:353)
... 99 more
spring-servlet.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<!-- Auto-balayage de classes dans le contexte / Auto-scan classes within the context -->
<context:annotation-config />
</beans>
WebConfig.java
package baseproject.web.configuration;
import java.util.Locale;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;
#Configuration
#EnableWebMvc
#ComponentScan(basePackages = { "baseproject" })
public class WebConfig extends WebMvcConfigurerAdapter {
#Bean
public ResourceBundleMessageSource messageSource() {
ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
String[] strBaseNames = {
"resources.messages.layout.LayoutResources",
"resources.messages.global.GlobalResources",
"resources.messages.welcome.WelcomeResources",
"resources.messages.user.UserResources",
"resources.messages.role.RoleResources",
"resources.messages.profile.ProfileResources"
};
messageSource.setUseCodeAsDefaultMessage(true);
messageSource.setDefaultEncoding("UTF-8");
messageSource.setBasenames(strBaseNames);
return messageSource;
}
#Bean
public LocaleChangeInterceptor localeChangeInterceptor() {
LocaleChangeInterceptor result = new LocaleChangeInterceptor();
result.setParamName("language");
return result;
}
#Bean
public LocaleResolver localeResolver() {
SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
sessionLocaleResolver.setDefaultLocale(Locale.ENGLISH);
return sessionLocaleResolver;
}
#Override
public void addInterceptors(InterceptorRegistry interceptorRegistry) {
interceptorRegistry.addInterceptor(localeChangeInterceptor());
}
#Override
public void addResourceHandlers(ResourceHandlerRegistry resourceHandlerRegistry) {
resourceHandlerRegistry.addResourceHandler("/static/**").addResourceLocations("/static/");
}
#Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/").setViewName("views/welcome/welcomePage");
}
}
Finally, my libs :
aopalliance-1.0.jar
GlobalLibraries.jar
hibernate-core-4.2.8.Final.jar
hibernate-entitymanager-4.2.8.Final.jar
javax.servlet-api-3.0.1.jar
jcifs-1.3.17.jar
jdo-api-3.0.jar
libs.txt
ognl-3.0.6.jar
openjpa-all-2.2.1.jar
slf4j-api-1.6.6.jar
slf4j-log4j12-1.7.5.jar
spring-aop-4.0.2.RELEASE.jar
spring-aspects-4.0.2.RELEASE.jar
spring-beans-4.0.2.RELEASE.jar
spring-context-4.0.2.RELEASE.jar
spring-context-support-4.0.2.RELEASE.jar
spring-core-4.0.2.RELEASE.jar
spring-expression-4.0.2.RELEASE.jar
spring-framework-bom-4.0.2.RELEASE.jar
spring-instrument-4.0.2.RELEASE.jar
spring-jdbc-4.0.2.RELEASE.jar
spring-jms-4.0.2.RELEASE.jar
spring-ldap-core-2.0.1.RELEASE.jar
spring-ldap-core-tiger-2.0.1.RELEASE.jar
spring-messaging-4.0.2.RELEASE.jar
spring-orm-4.0.2.RELEASE.jar
spring-oxm-4.0.2.RELEASE.jar
spring-security-config-3.2.2.RELEASE.jar
spring-security-core-3.2.2.RELEASE.jar
spring-security-ldap-3.2.3.RELEASE.jar
spring-security-web-3.2.2.RELEASE.jar
spring-test-4.0.2.RELEASE.jar
spring-tx-4.0.2.RELEASE.jar
spring-web-4.0.2.RELEASE.jar
spring-webmvc-4.0.2.RELEASE.jar
spring-webmvc-portlet-4.0.2.RELEASE.jar
spring-websocket-4.0.2.RELEASE.jar
thymeleaf-2.1.2.RELEASE.jar
thymeleaf-spring4-2.1.2.RELEASE.jar
I know that's a lot of code but I wanted to provide as much details as possible.
THANK YOU for help.
I know this question is over 9 month old, but I stumbled over the same problem and managed to fix it. The solution from Andrei Stefan is one step in the right direction. Surprisingly, when you call getObject() within the method to retrieve the entityManagerFactory, it will throw a NPE, but if you call the exact same method outside of the entityManagerFactory method it will work.
#Bean
public PlatformTransactionManager transactionManager() {
return new JpaTransactionManager(entityManagerFactory().getObject());
}
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
factory.setDataSource(dataSource());
HibernateJpaVendorAdapter jpaVendorAdapter = new HibernateJpaVendorAdapter();
jpaVendorAdapter.setGenerateDdl(true);
jpaVendorAdapter.setDatabasePlatform("org.hibernate.dialect.H2Dialect");
factory.setJpaVendorAdapter(jpaVendorAdapter);
return factory;
}
#Bean
public DataSource dataSource() {
return new EmbeddedDatabaseBuilder().setType(EmbeddedDatabaseType.H2).build();
}
The initialization logic of LocalContainerEntityManagerFactoryBean is in the afterPropertiesSet() method. Usually it is called by Spring after all properties have been set. You have to call afterPropertiesSet() before calling getObject() if you manually instantiate the bean. Otherwise you'll get a NullPointerException.
Try
#Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
...
return localContainerEntityManagerFactoryBean;
}
instead of
#Bean
public EntityManagerFactory entityManagerFactory() {
...
return localContainerEntityManagerFactoryBean.getObject();
}
#charleyDc5 does your application context (spring-servlet.xml) includes
< context:component-scan >. Is the #repository package included in it. some times this might be a cause for this issue.

Resources