Issue
I have spring boot application where I am stuck not sure what's wrong in my code. It gives me error of beans creation. I have used @Autowired, but not sure what's wrong.
Main.Java
@SpringBootApplication
public class Application
{
public static void main(String[] args)
{
SpringApplication.run(Application.class, args);
}
}
UserWS.java
@Controller
public class UserWS
{
@Autowired
UserService userService;
@RequestMapping(value = URLConstants.ADD, method = RequestMethod.POST)
@ResponseBody
public ResponseEntity<Status> add(@RequestBody User user) throws PeerRateException
{
try
{
userService.addUser(user);
Status status = PeerUtils.getSuccessStatus();
status.setObject(null);
return new ResponseEntity<>(status, HttpStatus.OK);
}
catch (Throwable t)
{
throw new PeerRateException(ExceptionConstants.USER_CREATE_CODE, ExceptionConstants.USER_CREATE, t);
}
}
}
UserService.Java
@Component
public class UserService
{
@Autowired
private UserDao userDao;
public void addUser(User user)
{
userDao.save(user);
}
}
UserDao.java
@Transactional
public interface UserDao extends CrudRepository<User, Long>
{
}
EDIT
com.hk.peerrate.main
Main.java
com.hk.peerrate.service
UserService.java
com.hk.peerrate.ws
UserWS.java
Solution
Since you haven't displayed the package where all above class resides, I can only assume that the problem is with your Project structure.
The UserService
class could be outside of the @ComponentScan
.
Now @SpringBootApplication
is same as @Configuration @EnableAutoConfiguration @ComponentScan
together, so make sure that the UserService.java
is under the same package or sub-package of your Application.java
.
Have a look at the this Spring Boot doc.
Answered By - Sanjay Rawat
Answer Checked By - David Goodson (JavaFixing Volunteer)