Why does spring boot behave abnormally sometimes ? - Cannot find Autowired class - java

I have been experimenting with spring boot since a while now, and I have noticed few strange things. Sometimes we have to include #ComponentScan in main class to solve the error which goes like try defining the bean of type package.name .
For eg. I created many sprint boot application without including #ComponentScan or any such annotation like #EnableJpaRepositories but recently I created one spring boot project which says Cannot find bean of type RepositoryName and when I used #ComponentScan , It worked. Why is that ?
You can see the code below:
Spring Class:
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.ComponentScan;
#ComponentScan(basePackages = {"com.example.demo.repository"})
#SpringBootApplication
public class SampleApplication {
public static void main(String[] args) {
SpringApplication.run(SampleApplication.class, args);
}
}
Entity Class:
package com.example.demo.entity;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import org.hibernate.annotations.GenericGenerator;
import org.springframework.data.annotation.Id;
import lombok.Data;
#Entity(name = "admin")
#Data
public class Admin {
#Id
#GenericGenerator(name = "admin_id_seq" , strategy = "increment")
#GeneratedValue(generator="admin_id_seq",strategy = GenerationType.AUTO)
private Long id;
private String username;
private String password;
private String name;
}
Controller
package com.example.demo.controller;
import com.example.demo.dto.AdminRegisterDTO;
import com.example.demo.repository.AdminRepository;
import com.example.demo.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class AdminController {
#Autowired
private AdminService adminService;
#PostMapping("/login")
public AdminRegisterDTO registerAdmin(#RequestBody AdminRegisterDTO adminRegisterDTO){
return adminService.registerAdmin(adminRegisterDTO);
}
}
Service class
package com.example.demo.service.impl;
import com.example.demo.dto.AdminRegisterDTO;
import com.example.demo.entity.Admin;
import com.example.demo.repository.AdminRepository;
import com.example.demo.service.AdminService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class AdminServiceImpl implements AdminService {
#Autowired
private AdminRepository adminRepository;
#Override
public AdminRegisterDTO registerAdmin(AdminRegisterDTO adminRegisterDTO) {
Admin admin = new Admin();
BeanUtils.copyProperties(adminRegisterDTO,admin);
Admin savedAdmin = adminRepository.save(admin);
AdminRegisterDTO adminRegisterDTO1 = new AdminRegisterDTO();
BeanUtils.copyProperties(savedAdmin,adminRegisterDTO1);
return adminRegisterDTO1;
}
}
Repository:
package com.example.demo.repository;
import com.example.demo.entity.Admin;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface AdminRepository extends JpaRepository<Admin, Long> {
}
If I remove #ComponentScan I get the following error message:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field adminRepository in com.example.demo.service.impl.AdminServiceImpl required a bean of type 'com.example.demo.repository.AdminRepository' 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.example.demo.repository.AdminRepository' in your configuration.

Related

Spring book throws Field postRepository in required a bean of type 'repository.PostRepository' that could not be found

I am aware that there are a lot of questions related to the same but none of them worked for some reason. Hence, posting the same and hoping to get some response.
I am trying to follow the SpingBoot application tutorial from Youtube and build the same application. But for some reason I get following error:
***************************
APPLICATION FAILED TO START
***************************
Description:
Field postRepository in com.testingconverter.service.PostService required a bean of type 'com.testingconverter.repository.PostRepository' 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.testingconverter.repository.PostRepository' in your configuration.
Following are my classes:
Main SpringBootApplication class:
package com.testingconverter;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class})
public class TestingConverterApplication {
public static void main(String[] args) {
SpringApplication.run(TestingConverterApplication.class, args);
}
}
Controller class:
package com.testingconverter.controller;
import com.testingconverter.entities.PostEntity;
import com.testingconverter.service.PostService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class BlogController {
#Autowired
private PostService postService;
#GetMapping(value = "/")
public String index() {
return "index";
}
#GetMapping(value = "/posts")
public List<PostEntity> posts() {
return postService.getAllPost();
}
#PostMapping(value = "/posts")
public void publishPost(#RequestBody PostEntity post) {
postService.insert(post);
}
}
My Entity class:
package com.testingconverter.entities;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import java.util.Date;
#Entity
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#ToString
public class PostEntity {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
private String title;
private String body;
private Date date;
}
My Repository class:
package com.testingconverter.repository;
import com.testingconverter.entities.PostEntity;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface PostRepository extends JpaRepository<PostEntity, Long> {
}
My Service class:
package com.testingconverter.service;
import com.testingconverter.entities.PostEntity;
import com.testingconverter.repository.PostRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
#Service
public class PostService {
#Autowired
private PostRepository postRepository;
public List<PostEntity> getAllPost() {
return postRepository.findAll();
}
public void insert(PostEntity post) {
postRepository.save(post);
}
}
I tried many things like adding the #ComponentScan etc but nothing seems to work for me. Can someone please explain to me what's going wrong here? How can I fix this?
Following is my project structure:
You excluding default database configuration. Remove that exclude part and add your database configuration in application properties files.
If you going to exclude then you have to create you datasource in configuration file.
#Bean
public DataSource getDataSource() {
DataSourceBuilder dataSourceBuilder =
DataSourceBuilder.create();
dataSourceBuilder.driverClassName("");
dataSourceBuilder.url("");
dataSourceBuilder.username("");
dataSourceBuilder.password("");
return dataSourceBuilder.build();
}

what is the problem using java spring boot

I try to search all data using java-spring-boot with Mysql but when i run the code i got the this error
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'emp0_.get_company_name' in 'field list'
This is my Controller code
package com.example.rest.controller;
import com.example.rest.Emp;
import com.example.rest.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
#RequestMapping("emp")
public class EmpController {
#Autowired
private EmpService empService;
#GetMapping(produces = {MediaType.APPLICATION_JSON_VALUE})
public ResponseEntity<List<Emp>> getAllEmps() {
List<Emp> emps = empService.findAll();
return new ResponseEntity<List<Emp>>(emps,HttpStatus.OK);
}
}
This is my EmpRepository code
package com.example.rest.repository;
import com.example.rest.Emp;
import org.springframework.data.jpa.repository.JpaRepository;
import java.util.List;
public interface EmpRepository extends JpaRepository<Emp, Integer> {
}
This is my EmpService Code
package com.example.rest.service;
import com.example.rest.Emp;
import java.util.List;
public interface EmpService {
List<Emp> findAll();
}
This is my EmpServiceImpl Code
package com.example.rest.service;
import com.example.rest.Emp;
import com.example.rest.repository.EmpRepository;
import org.springframework.beans.factory.annotation.Autowired;
import java.util.ArrayList;
import java.util.List;
#Service
public class EmpServiceImpl implements EmpService {
#Autowired
private EmpRepository empRepository;
#Override
public List<Emp> findAll() {
List<Emp> emps= new ArrayList<>();
empRepository.findAll().forEach((e -> emps.add(e)));
return emps;
}
}
This is my Application Code
package com.example.rest;
import com.example.rest.repository.EmpRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
#SpringBootApplication
#Configuration
public class Application {
#Autowired
EmpRepository empRepository;
public static void main(String[] args) {
SpringApplication.run(Application.class , args);
}
}
This is my Emp Code
package com.example.rest;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "company")
#Data
#AllArgsConstructor
#NoArgsConstructor
public class Emp implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
private Integer idx;
private String company_id;
private String getCompany_name;
}
So if someone knows that what is the problem please tell me if you don't remind with solution
Thank you!
Use #Service annotation on the EmpServiceImpl class and #Repository annotation on the EmpRepository.
#Service
public class EmpServiceImpl implements EmpService {
#Autowired
private EmpRepository empRepository;
#Override
public List<Emp> findAll() {
List<Emp> emps= new ArrayList<>();
empRepository.findAll().forEach((e -> emps.add(e)));
return emps;
}
}
#Repository
public interface EmpRepository extends JpaRepository<Emp, Integer> {
}
Need to add annotation on below class:
#Service
class EmpServiceImpl implements EmpService {
}

Spring boot does not generate the json and shows me the white page

I've done a simple list with sql server, but it doesn't show me the result, it just shows me the white page.
I have no error in the console. Will the sql server 2017 be? please any help?
connection to sql server 2017
spring.datasource.driver-class-name=com.microsoft.sqlserver.jdbc.SQLServerDriver
spring.datasource.url=jdbc:sqlserver://localhost;databaseName=DB_PRUEBA_V1;integratedSecurity=true
spring.jpa.show-sql=true
#spring.jpa.hibernate.ddl-auto=update
server.port=8090
package app
package app;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ProyectoV2Application {
public static void main(String[] args) {
SpringApplication.run(ProyectoV2Application.class, args);
}
}
package model
package model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "TB_USERS")
public class Users implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "COD_USER")
private int codUser;
#Column(name = "NOM_USER")
private String nomUser;
#Column(name = "EMA_USER")
private String emUser;
public int getCodUser() {
return codUser;
}
public void setCodUser(int codUser) {
this.codUser = codUser;
}
public String getNomUser() {
return nomUser;
}
public void setNomUser(String nomUser) {
this.nomUser = nomUser;
}
public String getEmUser() {
return emUser;
}
public void setEmUser(String emUser) {
this.emUser = emUser;
}
}
package repository
package repository;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import model.Users;
#Repository
public interface UserDAO extends JpaRepository<Users, Integer>{
}
service
package service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import model.Users;
import repository.UserDAO;
#Service
public class UserService {
#Autowired
private UserDAO dao;
public List<Users> lista(){
return dao.findAll();
}
}
package controller
package controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import model.Users;
import service.UserService;
#RestController
#RequestMapping(value = "/CrudUsers")
public class UserController {
#Autowired
private UserService us;
#ResponseBody
#GetMapping(path = "/lista", produces = MediaType.APPLICATION_JSON_VALUE)
public List<Users> lista(){
return us.lista();
}
}
Whitelabel Error Page
Because you created each class in different package like below,
app --> ProyectoV2Application
model --> Users
repository --> UserDAO
service --> UserService
controller --> UserController
But spring boot scans the classes that are either in root package or in sub package of root package, so move all these classes into sub packages of root package
app --> ProyectoV2Application
app.model --> Users
app.repository --> UserDAO
app.service --> UserService
app.controller --> UserController

Added #Transactional into a test to avoid org.hibernate.LazyInitializationException no Session error. Why is it needed?

I annotated a test method with #Transactional to avoid:
org.hibernate.LazyInitializationException: could not initialize proxy [com....OrderEntity#6def569a-ebf2-473e-b1b1-8b67e62fd17d] - no Session
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:169)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:309)
at org.hibernate.proxy.pojo.bytebuddy.ByteBuddyInterceptor.intercept(ByteBuddyInterceptor.java:45)
at org.hibernate.proxy.ProxyConfiguration$InterceptorDispatcher.intercept(ProxyConfiguration.java:95)
at com...orders.OrderEntity$HibernateProxy$wwLGAOuY.getDescription(Unknown Source)
I do not know why it is needed and wonder whether my application configuration is correct.
import lombok.Getter;
import lombok.Setter;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Date;
import java.util.UUID;
#Entity
#Table(name = "orders")
#Getter
#Setter
public class OrderEntity {
#Id
#GeneratedValue
private UUID uid;
private Date created;
private Date updated;
private String description;
}
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.UUID;
#Repository
public interface OrderRepository extends JpaRepository<OrderEntity, UUID> {
List<OrderEntity> findByDescription(String description);
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.UUID;
#Service
#Transactional
public class OrderService
{
private OrderRepository repository;
#Autowired
public OrderService(OrderRepository repository) {
this.repository = repository;
}
public List<OrderEntity> findAll() {
return repository.findAll();
}
public OrderEntity save(OrderEntity order) {
return repository.save(order);
}
public OrderEntity getOne(UUID uid) {
return repository.getOne(uid);
}
}
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.transaction.annotation.Transactional;
import static org.junit.Assert.assertEquals;
#RunWith(SpringRunner.class)
#SpringBootTest
public class OrderServiceTest {
#Autowired
private OrderService service;
#Test
#Transactional
public void testSave() {
OrderEntity order = new OrderEntity();
order.setDescription("Order description");
OrderEntity saved = service.save(order);
System.out.println(saved.getDescription());
OrderEntity persisted = service.getOne(saved.getUid());
// throws LazyInitializationException without #Transactional
System.out.println(persisted.getDescription());
assertEquals(persisted.getDescription(), order.getDescription());
}
}
I even added #EnableTransactionManagement but it makes no difference:
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
public class PersistenceJPAConfig {
}
The difference between getOne and findOne is that the first always returns a lazy proxy, even if there is no actual row in the database. The lazy proxy needs an open EntityManager to operate on. However as your test method doesn't run in a single transaction the EntityManager will be closed as soon as the getOnemethod ends.
Without an open EntityManager calls on the object will fail as it cannot retrieve the values from the database anymore.
To solve use findOne instead of getOne OR make your test method transactional. The latter however has some other effects on your test-case (it will return the same object from the findOne call as it will also reuse a single EntityManager).

Parameter 0 of constructor in Thomas.ChapterController required a bean of type 'Thomas.ChapterRepository' that could not be found

I'm new to spring boot and I can't get an example from my spring boot book to work. Here is the code
Description:
Parameter 0 of constructor in Thomas.ChapterController required a bean of >type 'Thomas.ChapterRepository' that could not be found.
Action:
Consider defining a bean of type 'Thomas.ChapterRepository' in your configuration.
Chapter.java
package Thomas;
import lombok.Data;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Data
#Document
public class Chapter {
#Id /*tells mongodb that this will be the primary key for Mongo Document */
private String Id;
private String name;
public Chapter(String name) {
this.name = name;
}
}
ChapterRepository.java
package Thomas;
import org.springframework.data.repository.reactive.ReactiveCrudRepository;
public interface ChapterRepository extends ReactiveCrudRepository<Chapter, String> {
}
LoadDatabase.Java
package Thomas;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import reactor.core.publisher.Flux;
import org.springframework.context.annotation.Configuration;
#Configuration /* Marks this class as a source of beans */
public class LoadDatabase {
#Bean /* Indicates that the return value of init is a Spring Bean */
CommandLineRunner init(ChapterRepository repository) {
return args -> {
Flux.just (
new Chapter("Quick Start With Java"),
new Chapter("Reactive Web With Spring Boot"),
new Chapter("...and More!"))
.flatMap(repository::save)
.subscribe(System.out::println);
};
}
}
ChapterController.java
package Thomas;
import reactor.core.publisher.Flux;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
#RestController
public class ChapterController {
private final ChapterRepository repository;
public ChapterController(ChapterRepository repository)
{
this.repository = repository;
}
#GetMapping("/chapters")
public Flux<Chapter> listing() {
return repository.findAll();
}
}
ThomasSpringApplication.java
package Thomas;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class ThomasSpringApplication {
public static void main(String [] args) {
SpringApplication.run(ThomasSpringApplication.class, args);
}
}
Figured out i was pulling in the wrong dependencies in my pom.xml

Categories