org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies - spring

Can any one solve this
i am getting the below error which runs on eclipse
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'personController': Injection of autowired dependencies failed; nested
exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.service.CustomerService
com.spring.controller.PersonController.customerService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name
'customerService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.spring.repository.CustomerRepository com.spring.service.CustomerServiceImpl.customerRepository; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [com.spring.repository.CustomerRepository] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
i have the following
1.PersonController (class)
2.Person (class)
3.CustomerService (interface)
4.CustomerServiceImpl (class)
5.CustomerRepository (interface)
package com.spring.controller
in PersonController (class)
=====================
#Autowired
private CustomerService customerService;
#RequestMapping(value = "/person", method = RequestMethod.GET)
public String getPersonList(ModelMap model) {
model.addAttribute("personList", customerService.findAlls());
return "output";
}
package com.spring.service
in CustomerService (interface)
==================
public List<Person> findAlls();
package com.spring.service
in CustomerServiceImpl
=====================
#Service("customerService")
public class CustomerServiceImpl implements CustomerService {
#Autowired
private CustomerRepository customerRepository;
public List<Person> findAlls() {
List<Person> usersList = customerRepository.findAll();
return null;
}
}
package com.spring.repository
in CustomerRepository
===========================
#Repository("customerRepository")
public interface CustomerRepository extends MongoRepository<Person, String> {
public List<Person> findAll();
}
thanks and regards

Related

use spring-data-r2dbc, Unable to inject DAO interface,Field myDao in ServiceImpl required a bean of type 'UmsAddressDao' that could not be found

1.illustrate
springboot 2.3.7
springboot-data-r2dbc 1.1.6
2.I used Spring-Data-R2DBC to operate mysql, but I have been reporting an errororg.springframework.beans.factory.UnsatisfiedDependencyException
3.Complete error description
cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'webFluxController': Unsatisfied dependency expressed through field 'umsAddressService'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'umsAddressServiceImpl': Unsatisfied dependency expressed through field 'umsAddressDao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.xxx.inner.UmsAddressDao' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Field umsAddressDao in com.xxx.impl.UmsAddressServiceImpl required a bean of type 'com.xxx.inner.UmsAddressDao' that could not be found.
3.My code snippet
my controller
#RestController
public class WebFluxController {
private Logger log = LoggerFactory.getLogger(WebFluxController.class);
#Autowired
private UmsAddressService umsAddressService;
#Autowired
private StringRedisTemplate stringRedisTemplate;
#Autowired
private QuestionService questionService;
// do something
}
my service
public interface UmsAddressService {
Mono<UmsAddress> findById(Long id);
}
my service impl
#Service
public class UmsAddressServiceImpl implements UmsAddressService {
#Autowired
private UmsAddressDao umsAddressDao;
#Override
public Mono<UmsAddress> findById(Long id) {
return umsAddressDao.findById(id);
}
}
my dao
#Component
public interface UmsAddressDao extends ReactiveCrudRepository<UmsAddress,Long> {
}
my model
#Data
#Accessors(chain = true)
#ToString
#Table("ums_address")
public class UmsAddress {
#Id
#Column("id")
private Long id;
#Column("member_id")
private Long memberId;
// other field
}
springbootApplication
#EnableWebFlux
#SpringBootApplication( exclude = { RedisRepositoriesAutoConfiguration.class })
#OpenAPIDefinition(info = #Info(title = "APIs", version = "1.0", description = "Documentation APIs v1.0"))
public class MyWebApplication {
public static void main(String[] args) {
new SpringApplicationBuilder(RollkingWebApplication.class).web(WebApplicationType.REACTIVE).run(args);
}
}

No qualifying bean of type 'mypackage.repository' available: expected at least 1 bean which qualifies as autowire candidate

I have a test class in Junit4 that needs to use NutrientListService.
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
private NutrientListService nutrientService;
#Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}
I was getting a null nutrientService, so I tried to set up an ApplicationContext.
#Configuration
#ComponentScan("myservice")
#ComponentScan("myrepository")
public class ApplicationContext {
#Autowired
NutrientListService nutrientService;
}
However, I get
Error creating bean with name 'nutrientListService': Unsatisfied dependency expressed through field 'nutrientListRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'repositories.NutrientListRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
This is the service:
#Service
#Component
public class NutrientListService {
#Autowired
private NutrientListRepository repo;
}
And the repository:
#Repository
public interface NutrientListRepository extends MongoRepository<MyClass, String> {
MyClass findByID(String ID);
}
Any ideas to wire the service properly? I need to pass it for calculation as it is one of the parameters. Do I have to use an application context class or the application-context.xml (which I could not find)? What would be the least obscure way to do this? I thank you.
#Configuration
#ComponentScan("myservice")
#ComponentScan("myrepository")
public class ApplicationContext {
#Bean
NutrientListService nutrientService(){
new NutrientListService()
}
}
And then call the Bean with #Autowired
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(classes = ApplicationContext.class)
public class CalculationTests {
#Autowired
NutrientListService nutrientService
#Test
public void someTest()
Result re = Calculator.calculate(response, nutrientService)
}

Injection of autowired dependencies failed (spring and hibernate)

i found many topics about my error but not the same situation so i don't thing that this subject is duplicated.
here is the controller:
#ManagedBean
#Named
public class UserController {
#Inject
public UserManager userManager;
...
}
Dao:
#Named
#Transactional("transactionManager")
public class UserDAO {
#Inject
private SessionFactory sessionFactory;
//...
}
User manager :
#Named
public class UserManager {
#Inject
public UserDAO userDAO;
//...
}
UserModel (ModelView):
public class UserModel {
private String login;
private String pwd;
private String pwdConfirm;
//...
}
One to Many relation :
#Entity
#Table(name = "role", catalog = "dbusiness")
public class Role implements java.io.Serializable {
private int roleId;
private String code;
private String label;
private User user;
}
#Entity
#Table(name = "user", catalog = "dbusiness")
public class User implements java.io.Serializable {
private int userId;
private String login;
private String pwd;
private Integer enabled;
private Set<Role> roles = new HashSet<Role>(0);
}
User can have many roles, and one role can be affected in the sime time to many users, that's why i used One to many relation, i didn't put all lignes of code because of stackOverflow rules :p
So when i start tomcat server i get this error message :
Error creating bean with name 'userController': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.keylesson.manager.UserManager com.keylesson.controller.UserController.userManager; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userManager': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.keylesson.dao.UserDAO com.keylesson.manager.UserManager.userDAO; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userDAO': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.hibernate.SessionFactory com.keylesson.dao.UserDAO.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/spring-hibernate.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: An AnnotationConfiguration instance is required to use <mapping class="com.keylesson.persistence.User"/>

Unable to autowire dozer Mapper in component class in spring boot

I am new to Spring Boot. I was trying to develop small application in spring boot mvc with neo4j database. Following is my Server
#Configuration
#ComponentScan({ "myproject" })
#EnableAutoConfiguration
#EnableNeo4jRepositories(basePackages = "myproject")
public class Server extends Neo4jConfiguration implements CommandLineRunner
{
public Server()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
#Bean
Mapper mapper()
{
return new DozerBeanMapper();
}
public void run(String... args) throws Exception
{
}
public static void main(String[] args) throws Exception
{
SpringApplication.run(Server.class, args);
}
}
Following is my main class
#Configuration
#ComponentScan({ "myproject.business" })
#EnableNeo4jRepositories(basePackages = "myproject")
public class MainWithStructure extends Neo4jConfiguration implements CommandLineRunner
{
#Autowired
private MyService myService;
public MainWithStructure()
{
setBasePackage("myproject");
}
#Bean
SpringRestGraphDatabase graphDatabaseService()
{
return new SpringRestGraphDatabase("http://localhost:7474/db/data");
}
.......
......
public static void main(String[] args) throws Exception
{
FileUtils.deleteRecursively(new File("accessingdataneo4j.db"));
SpringApplication app = new SpringApplication(MainWithStructure.class);
app.setWebEnvironment(false);
app.run(args);
}
}
Following is my Component class
#Component
public class MyService
{
#Autowired
private Mapper mapper; //Fails to autowire org.dozer.Mapper
.....
}
Following is my Controller class
#RestController
#RequestMapping("/rest")
public class MyController
{
#Autowired
private Mapper mapper; //autowire sucess org.dozer.Mapper
}
I got following Exception when I run main class MainWithStructure
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'mainWithStructure': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private myproject.business.MyService myproject.main.MainWithStructure.MyService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private org.dozer.Mapper myproject.business.MyService.mapper; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.dozer.Mapper] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
Following is my project structure
demo_project
src/main/java
---myproject.main
------MainWithStructure.java
------Server.java
---myproject.business
------MyService.java
---myproject.rest
------MyController.java
If I autowire org.dozer.Mapper in Controller, it sucessfuly autowired it. BUT if I autowire org.dozer.Mapper in Component class it fails to autowire.
Why it is failing to autowire org.dozer.Mapper only on Component class?
Please make me correct if I wrong. Thank you :)
Your Server is not in one of the packages that you #ComponentScan, so the Mapper is indeed not a bean. Try removing the explicit package from the #ComponentScan (since everything is in a subpackage of the main class that will pick up all the components).
You can add #SpringBootApplication in your main class which has #ComponentScan
which will scan all your sub components in project.

error with project in spring, hibernate

This the error that I'm getting:
SEVERE: StandardWrapper.Throwable
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'usuarioControlador': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.blah.base.database.DAO.UsuarioDAO com.blah.base.controlador.UsuarioControlador.usuarioDAO; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'UsuarioDAO' defined in file [C:\Users\Owner\workspaceSpring.metadata.plugins\org.eclipse.wst.server.core\tmp3\wtpwebapps\base\WEB-INF\classes\com\yavale\base\database\hibernetDAO\UsuarioHibernetDao.class]: Unsatisfied dependency expressed through constructor argument with index 0 of type [org.hibernate.SessionFactory]: : No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [org.hibernate.SessionFactory] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {#org.springframework.beans.factory.annotation.Qualifier(value=sessionFactory)}
This is my UsuarioControlador (controller):
#Controller
#RequestMapping("/")
public class UsuarioControlador {
private UsuarioDAO usuarioDAO;
#Autowired
public void setUsuarioDAO(UsuarioDAO usuarioDAO) {
this.usuarioDAO = usuarioDAO;
}
#RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
List<Usuario> usuarios = usuarioDAO.listarUsuarios();
model.addAttribute("usuarios", usuarios);
return "index";
}
}
This is UsuarioDAO:
public interface UsuarioDAO {
void insertarUsuario(Usuario usuario);
void modificarUsuario(Usuario usuario);
List<Usuario> listarUsuarios();
Usuario buscarUsuario(String idUsuario);
void eliminarUsuario(Usuario usuario);
}
This is the class that implements UsuarioDAO:
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.stereotype.Service;
#Service(value="UsuarioDAO")
public class UsuarioHibernetDao extends HibernateDaoSupport implements UsuarioDAO{
#Autowired
public UsuarioHibernetDao(#Qualifier("mySessionFactory") SessionFactory
sessionFactory) {
this.setSessionFactory(sessionFactory);
}
public void insertarUsuario(Usuario usuario) {
this.getHibernateTemplate().save(usuario);
}
public void modificarUsuario(Usuario usuario) {
this.getHibernateTemplate().update(usuario);
}
public List<Usuario> listarUsuarios() {
return this.getHibernateTemplate().find("from Usuario");
}
public Usuario buscarUsuario(String idUsuario) {
return this.getHibernateTemplate().load(Usuario.class, idUsuario);
}
public void eliminarUsuario(Usuario usuario) {
this.getHibernateTemplate().delete(usuario);
}
}
This is my servlet-context.xml: https://dl.dropboxusercontent.com/u/31349296/servlet-context.xml
I'm new with spring so Im completely lost with this.
Edit: this is the complete stack trace: https://dl.dropboxusercontent.com/u/31349296/log.txt
Edit2:
You are using the wrong identifier in the Qualifier annotation. The bean id is "mySessionFactory" but you have given "sessionFactory". Also, make sure content component scan is scanning the right packages.
Update:
The other error is probably related to the import of the hibernate session. You should be using org.hibernate.Session instead of org.hibernate.classic.Session

Resources