Access ServiceBean from EJB3 - ejb-3.0

i implements this tutorial, but i cant access the service from EJB3.
My ejb looks like this:
#Stateless
public class Authentication implements AuthenticationRemote {
private ServiceTwoManagement man;
...
}
#EJB will throw: java.lang.RuntimeException: Could not resolve #EJB reference:
Any Suggestions

You guys had no chance to post an concrete answer (many informations hidden), i currently found either an clean solution or an buggy workaround. In second case: i would be glad to see any better solution like i found.
My solution was to create an service-bean (3rd bean) hold's all the TransportObjects.
#Service defines an Singleton, so i get close to the GoF-Pattern using the Singleton-Pattern.
Finally my solution looks like this:
package org.gegenakw.ejb.user;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import java.util.logging.Logger;
import javassist.NotFoundException;
import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.PersistenceContext;
import org.antiakw.exceptions.authentication.AccountAlreadyExistsException;
import org.antiakw.exceptions.authentication.IllegalLoginException;
import org.antiakw.exceptions.authentication.NotYetActivatedException;
import org.gegenakw.Utils;
import org.gegenakw.ejb.extern.RegistrationEmailsTransportObjectHolder;
import org.gegenakw.ejb.interfaces.RegistrationTransferObject;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.Restrictions;
import org.hibernate.validator.InvalidStateException;
import org.jboss.ejb3.annotation.Depends;
import de.antiakw.jpa.beans.Benutzer;
/**
* Session Bean implementation class Authentication
*/
#Stateless
public class Authentication implements AuthenticationRemote {
public static Logger log = Logger.getLogger("Authentication");
#PersistenceContext(unitName = "gegenakwjpa")
Session hibernateSession;
// #EJB
private List<RegistrationTransferObject> registration = RegistrationEmailsTransportObjectHolder.getInstance();
#Override
public void createAccountCheckDuplicates(String email, String pass)
throws InvalidStateException, AccountAlreadyExistsException {
...
}
...
}
My RETOH looks like this:
package org.gegenakw.ejb.extern;
import java.util.ArrayList;
import java.util.List;
import javax.annotation.PostConstruct;
import org.gegenakw.ejb.interfaces.RegistrationTransferObject;
import org.jboss.ejb3.annotation.Management;
import org.jboss.ejb3.annotation.Service;
#Service(objectName = "gegen-akw:service=RETOH")
#Management(List.class)
public class RegistrationEmailsTransportObjectHolder extends ArrayList<RegistrationTransferObject> {
private static RegistrationEmailsTransportObjectHolder me;
public static RegistrationEmailsTransportObjectHolder getInstance() {
return me;
}
#PostConstruct
public void create() throws Exception {
me = this;
}
}
And my Job looks like this:
package de.antiakw.service.email;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.Provider;
import java.security.Security;
import java.security.cert.X509Certificate;
import java.util.List;
import java.util.logging.Logger;
import javax.annotation.Resource;
import javax.ejb.ActivationConfigProperty;
import javax.ejb.MessageDriven;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.mail.smime.SMIMEException;
import org.bouncycastle.mail.smime.SMIMESignedGenerator;
import org.gegenakw.ejb.interfaces.RegistrationTransferObject;
import org.jboss.ejb3.annotation.Depends;
import org.jboss.ejb3.annotation.ResourceAdapter;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
#ResourceAdapter("quartz-ra.rar")
#MessageDriven(activationConfig = { #ActivationConfigProperty(propertyName = "cronTrigger", propertyValue = "0 * * * * ?") }
)
public class RegistrationEmails implements Job {
public static final Logger log = Logger.getLogger("RegistrationEmails");
private static java.security.cert.Certificate certificate;
#Depends("gegen-akw:service=RETOH")
private List<RegistrationTransferObject> registrationMailHolder;
#Resource(mappedName = "java:Gegen-AKW-Mailsystem")
javax.mail.Session mailSession;
#Override
public void execute(JobExecutionContext arg0) throws JobExecutionException {
synchronized (registrationMailHolder) {
#JavaKaBaby: to folow your needs, i post my stactrace using #EJB instad of singleton-pattern (i hope the problem is comprehesible withal my workaround):
09:51:21,577 ERROR [AbstractKernelController] Error installing to Real: name=vfs:///C:/jboss-6.1.0.Final/server/default/deploy/gegen-akw.ear state=PreReal mode=Manual requiredState=Real: org.jboss.dep
loyers.spi.DeploymentException: Error during deploy: org.jboss.metadata.ejb.jboss.JBossEnterpriseBeanMetaData.Authentication
at org.jboss.deployers.spi.DeploymentException.rethrowAsDeploymentException(DeploymentException.java:49) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:185) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doDeploy(DeployersImpl.java:1832) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1550) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1571) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.doInstallParentFirst(DeployersImpl.java:1603) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.install(DeployersImpl.java:1491) [:2.2.2.GA]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.deployers.plugins.deployers.DeployersImpl.change(DeployersImpl.java:1983) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployersImpl.process(DeployersImpl.java:1076) [:2.2.2.GA]
at org.jboss.deployers.plugins.main.MainDeployerImpl.process(MainDeployerImpl.java:679) [:2.2.2.GA]
at org.jboss.system.server.profileservice.deployers.MainDeployerPlugin.process(MainDeployerPlugin.java:106) [:6.1.0.Final]
at org.jboss.profileservice.dependency.ProfileControllerContext$DelegateDeployer.process(ProfileControllerContext.java:143) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileDeployAction.deploy(ProfileDeployAction.java:151) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileDeployAction.installActionInternal(ProfileDeployAction.java:94) [:0.2.2]
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:54) [jboss-kernel.jar:2.2.0.SP2]
at org.jboss.kernel.plugins.dependency.InstallsAwareAction.installAction(InstallsAwareAction.java:42) [jboss-kernel.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.action.SimpleControllerContextAction.simpleInstallAction(SimpleControllerContextAction.java:62) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.action.AccessControllerContextAction.install(AccessControllerContextAction.java:71) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractControllerContextActions.install(AbstractControllerContextActions.java:51) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractControllerContext.install(AbstractControllerContext.java:379) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.install(AbstractController.java:2044) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.incrementState(AbstractController.java:1083) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.executeOrIncrementStateDirectly(AbstractController.java:1322) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1246) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.resolveContexts(AbstractController.java:1139) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:939) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.dependency.plugins.AbstractController.change(AbstractController.java:654) [jboss-dependency.jar:2.2.0.SP2]
at org.jboss.profileservice.dependency.ProfileActivationWrapper$BasicProfileActivation.start(ProfileActivationWrapper.java:190) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationWrapper.start(ProfileActivationWrapper.java:87) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationService.activateProfile(ProfileActivationService.java:215) [:0.2.2]
at org.jboss.profileservice.dependency.ProfileActivationService.activate(ProfileActivationService.java:159) [:0.2.2]
at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.activate(AbstractProfileServiceBootstrap.java:112) [:0.2.2]
at org.jboss.profileservice.resolver.BasicResolverFactory$ProfileResolverFacade.deploy(BasicResolverFactory.java:87) [:0.2.2]
at org.jboss.profileservice.bootstrap.AbstractProfileServiceBootstrap.start(AbstractProfileServiceBootstrap.java:91) [:0.2.2]
at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:132) [:6.1.0.Final]
at org.jboss.system.server.profileservice.bootstrap.BasicProfileServiceBootstrap.start(BasicProfileServiceBootstrap.java:56) [:6.1.0.Final]
at org.jboss.bootstrap.impl.base.server.AbstractServer.startBootstraps(AbstractServer.java:827) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6]
at org.jboss.bootstrap.impl.base.server.AbstractServer$StartServerTask.run(AbstractServer.java:417) [jboss-bootstrap-impl-base.jar:2.1.0-alpha-6]
at java.lang.Thread.run(Thread.java:662) [:1.6.0_25]
Caused by: java.lang.RuntimeException: Could not resolve #EJB reference: [EJB Reference: beanInterface 'java.util.List', beanName 'null', mappedName 'null', lookupName 'null', owning unit 'ComponentDe
ploymentContext#848640405{org.jboss.metadata.ejb.jboss.JBossEnterpriseBeanMetaData.Authentication}'] for environment entry: env/org.gegenakw.ejb.user.Authentication/registration in unit ComponentDeplo
ymentContext#848640405{org.jboss.metadata.ejb.jboss.JBossEnterpriseBeanMetaData.Authentication}
at org.jboss.ejb3.jndi.deployers.resource.provider.AnnotatedEJBRefResourceProvider.provide(AnnotatedEJBRefResourceProvider.java:99) [:0.1.7]
at org.jboss.ejb3.jndi.deployers.resource.provider.AnnotatedEJBRefResourceProvider.provide(AnnotatedEJBRefResourceProvider.java:50) [:0.1.7]
at org.jboss.switchboard.mc.JndiEnvironmentProcessor.process(JndiEnvironmentProcessor.java:68) [:1.0.0-alpha-15]
at org.jboss.switchboard.mc.deployer.AbstractSwitchBoardDeployer.process(AbstractSwitchBoardDeployer.java:119) [:1.0.0-alpha-15]
at org.jboss.switchboard.mc.deployer.EJBEnvironmentSwitchBoardDeployer.internalDeploy(EJBEnvironmentSwitchBoardDeployer.java:87) [:1.0.0-alpha-15]
at org.jboss.deployers.spi.deployer.helpers.AbstractRealDeployer.deploy(AbstractRealDeployer.java:55) [:2.2.2.GA]
at org.jboss.deployers.plugins.deployers.DeployerWrapper.deploy(DeployerWrapper.java:179) [:2.2.2.GA]
... 45 more

Related

Error creating bean with name 'entityManagerFactory' defined in class path resource and Access denied for user #'localhost' (using password: NO)

I got this error "access denied for user using password=NO" where I already added the right password.please give me solution on this.
Here is the stack trace:
java.sql.SQLException: Access denied for user 'www.abcom.in'#'localhost' (using password: NO)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:129) ~[mysql- connector-java-8.0.26.jar:8.0.26]
at
com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122 ) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.ConnectionImpl.createNewIO(ConnectionImpl.java:828) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.ConnectionImpl.<init>(ConnectionImpl.java:448) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.ConnectionImpl.getInstance(ConnectionImpl.java:241) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at com.mysql.cj.jdbc.NonRegisteringDriver.connect(NonRegisteringDriver.java:198) ~[mysql-connector-java-8.0.26.jar:8.0.26]
at java.sql.DriverManager.getConnection(DriverManager.java:664) ~[na:1.8.0_292]
at java.sql.DriverManager.getConnection(DriverManager.java:208) ~[na:1.8.0_292]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriverManager(DriverManagerDataSource.java:155) ~[spring-jdbc-5.3.9.jar:5.3.9]
at org.springframework.jdbc.datasource.DriverManagerDataSource.getConnectionFromDriver(DriverManagerDataSource.java:146) ~[spring-jdbc-5.3.9.jar:5.3.9]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnectionFromDriver(AbstractDriverBasedDataSource.java:205) ~[spring-jdbc-5.3.9.jar:5.3.9]
at org.springframework.jdbc.datasource.AbstractDriverBasedDataSource.getConnection(AbstractDriverBasedDataSource.java:169) ~[spring-jdbc-5.3.9.jar:5.3.9]
at org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl.getConnection(DatasourceConnectionProviderImpl.java:122) ~[hibernate-core-5.4.32.Final.jar:5.4.32.Final]
at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess.obtainConnection(JdbcEnvironmentInitiator.java:180) ~[hibernate-core-
Application configuration file Program:
package com.training.newspringquerydsl.config;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.sql.DataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import com.querydsl.jpa.impl.JPAQueryFactory;
#Configuration
#ComponentScan(basePackages = "com")
public class AppConfiguration {
#Bean("datasource")
public DataSource getDataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setUsername(dataSource.getUsername());
dataSource.setPassword(dataSource.getPassword());
dataSource.setUrl("jdbc:mysql://localhost/springwebservices");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
return dataSource;
}
#Bean
public JPAQueryFactory getjpaQueryFactory() {
EntityManagerFactory emf = Persistence.createEntityManagerFactory(null);
EntityManager em = emf.createEntityManager();
JPAQueryFactory queryFactory = new JPAQueryFactory(em);
return queryFactory;
}
}
Application properties file:
spring.datasource.url=jdbc:mysql://localhost:3306/springwebservices
spring.datasource.Data-username=root
spring.datasource.Data-password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
The properties with username and password are wrong:
It must be:
spring.datasource.username=root
spring.datasource.password=root

Error creating bean with name 'projectController': Unsatisfied dependency expressed through field 'service';

I use the following configuration and code to create a spring boot application.
pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<parent>
<artifactId>jeecg-boot-parent</artifactId>
<groupId>org.jeecgframework.boot</groupId>
<version>2.3.0</version>
</parent>
<modelVersion>4.0.0</modelVersion>
<artifactId>my-pm-project</artifactId>
<dependencies>
<dependency>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-system-cloud-api</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
</dependency>
<dependency>
<groupId>org.jeecgframework.boot</groupId>
<artifactId>jeecg-boot-base-common</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-mongodb</artifactId>
</dependency>
</dependencies>
</project>
Controller:
package cn.my.pm.project.controller;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.oConvertUtils;
import cn.my.pm.project.entity.Project;
import cn.my.pm.project.service.IProjectService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
#RestController
#RequestMapping("/project/project")
#Slf4j
public class ProjectController extends JeecgController<Project, IProjectService> {
#Autowired
private IProjectService projectService;
#GetMapping(value = "/list")
public Result<?> queryPageList(Project project,
#RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
#RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
HttpServletRequest req) {
QueryWrapper<Project> queryWrapper = QueryGenerator.initQueryWrapper(project, req.getParameterMap());
Page<Project> page = new Page<Project>(pageNo, pageSize);
IPage<Project> pageList = projectService.page(page, queryWrapper);
return Result.OK(pageList);
}
#PostMapping(value = "/add")
public Result<?> add(#RequestBody Project project) {
projectService.save(project);
return Result.OK("add!");
}
#PutMapping(value = "/edit")
public Result<?> edit(#RequestBody Project project) {
projectService.updateById(project);
return Result.OK("edit!");
}
#DeleteMapping(value = "/delete")
public Result<?> delete(#RequestParam(name="id",required=true) String id) {
projectService.removeById(id);
return Result.OK("delete!");
}
#DeleteMapping(value = "/deleteBatch")
public Result<?> deleteBatch(#RequestParam(name="ids",required=true) String ids) {
this.projectService.removeByIds(Arrays.asList(ids.split(",")));
return Result.OK("batch delete!");
}
#GetMapping(value = "/queryById")
public Result<?> queryById(#RequestParam(name="id",required=true) String id) {
Project project = projectService.getById(id);
if(project==null) {
return Result.error("not found");
}
return Result.OK(project);
}
}
Service:
package cn.my.pm.project.service;
import cn.my.pm.project.entity.Project;
import com.baomidou.mybatisplus.extension.service.IService;
public interface IProjectService extends IService<Project> {
}
ServiceImpl:
package cn.my.pm.project.service.impl;
import cn.my.pm.project.entity.Project;
import cn.my.pm.project.mapper.ProjectMapper;
import cn.my.pm.project.service.IProjectService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
#Service
#Slf4j
public class ProjectServiceImpl extends ServiceImpl<ProjectMapper, Project> implements IProjectService {
}
Mapper:
package cn.my.pm.project.mapper;
import java.util.List;
import org.apache.ibatis.annotations.Param;
import cn.my.pm.project.entity.Project;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.springframework.stereotype.Service;
public interface ProjectMapper extends BaseMapper<Project> {
}
ProjectMapper.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.my.pm.project.mapper.ProjectMapper">
</mapper>
Entity:
package cn.my.pm.project.entity;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.math.BigDecimal;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import com.fasterxml.jackson.annotation.JsonFormat;
import org.springframework.format.annotation.DateTimeFormat;
import org.jeecgframework.poi.excel.annotation.Excel;
import org.jeecg.common.aspect.annotation.Dict;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;
#Data
#TableName("my_info")
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
private java.lang.String id;
private java.lang.String myName;
private java.lang.String myType;
private java.lang.String myType;
private java.lang.String myManager;
private java.lang.String myInfo;
private java.lang.String myDetails;
private java.lang.String myImage;
}
Application:
package cn.my;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAnnotationProcessorAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroAutoConfiguration;
import org.apache.shiro.spring.boot.autoconfigure.ShiroBeanAutoConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
#SpringBootApplication(exclude = {ShiroAnnotationProcessorAutoConfiguration.class, ShiroAutoConfiguration.class, ShiroBeanAutoConfiguration.class})
#EnableDiscoveryClient
#EnableFeignClients
public class ProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
But when I run the application,the error message is:
ERROR org.springframework.boot.SpringApplication:858 - Application run failed
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectController': Unsatisfied dependency expressed through field 'service'; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.my.pm.project.mapper.ProjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:849)
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:877)
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142)
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775)
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260)
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248)
at cn.my.ProjectApplication.main(ProjectApplication.java:18)
Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'projectServiceImpl': Unsatisfied dependency expressed through field 'baseMapper'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.my.pm.project.mapper.ProjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:596)
at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessProperties(AutowiredAnnotationBeanPostProcessor.java:374)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1395)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:592)
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515)
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320)
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318)
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199)
at org.springframework.beans.factory.config.DependencyDescriptor.resolveCandidate(DependencyDescriptor.java:277)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1247)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 19 common frames omitted
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'cn.my.pm.project.mapper.ProjectMapper' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoMatchingBeanFound(DefaultListableBeanFactory.java:1654)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:1213)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:1167)
at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:593)
... 32 common frames omitted
Disconnected from the target VM, address: '127.0.0.1:64977', transport: 'socket'
How to fix it?
Spring's complaint is that you haven't defined a Bean of type ProjectMapper, which it is saying that it needs to satisfy an Autowire request. Looking at your code, I don't see a definition for such a Bean in what you've shown us here.
The exact point of the problem is hidden, I'm guessing, because you aren't showing us the definition of the ServiceImpl class. My guess is that that's where the actual reference is that Spring is trying to wire up. Apparently, the field name is baseMapper.
Spring doesn't seem to find Mapper.
try
#Mapper
public interface ProjectMapper extends BaseMapper<Project> {
}
Or
#SpringBootApplication(exclude = {ShiroAnnotationProcessorAutoConfiguration.class,
ShiroAutoConfiguration.class, ShiroBeanAutoConfiguration.class})
#EnableDiscoveryClient
#EnableFeignClients
#MapperScan(basePackage="cn.my.pm.project.mapper.*")
public class ProjectApplication {
public static void main(String[] args) {
SpringApplication.run(ProjectApplication.class, args);
}
}
The reason is that the package is not added with #MapperScan.
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
#Configuration
#MapperScan(value={"org.abc.modules.**.mapper*", "cn.my.pm.**.mapper*"})
public class MybatisPlusConfig {
……
}
Then there is no error.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'environment' available

I am getting this following exception on my production while running my code. I don't know what I am making mistake, the same code is happily running on my local machine, please help
Feb 19 13:46:40 ip-10-0-77-139 server: ShopifyGetItems: Service
function shop.getShopifyDomain():
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'hibernateConfig': Injection of autowired
dependencies failed; nested exception is
org.springframework.beans.factory.NoSuchBeanDefinitionException: No
bean named 'environment' available
import java.util.Properties;
import javax.sql.DataSource;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
import org.springframework.orm.hibernate4.HibernateTransactionManager;
import org.springframework.orm.hibernate4.LocalSessionFactoryBean;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#ComponentScan({ "com.webbee.app" })
#PropertySource(value = { "classpath:internal.properties" })
public class HibernateConfig {
#Autowired
private Environment environment;
private Properties hibernateProperties() {
System.out.println(environment.getRequiredProperty("hibernate.dialect"));
Properties properties = new Properties();
properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
properties.put("hibernate.jdbc.batch_size", 1000); // batch size for save or update
return properties;
}
}
It will be good, if you can debug the issue -
System.out.println("Created beans: " + Arrays.toString(context.getBeanNamesForType(Environment.class)));
if you are getting empty list it means, your bean is not instantiated in spring container and there is some problem with component scan.
This helped me in spring boot 2.4 but not in 2.6
spring:
config:
use-legacy-processing: false

Eureka and Feign MicroWebservice failing to startup

i have managed to build a microservice with one Eureka server and two client servers, one of the server is using Feign and ribbon to call other service , and this service is getting shutdown immediately after startup. i tried to search for possible problem but i couldn't find any. please help me to resolve it.
controller class
package com.booter.Company.controller;
import java.util.List;
import javax.websocket.server.PathParam;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.booter.Company.dto.CompanyDTO;
import com.booter.Company.dto.EmployeeDTO;
#RestController
#RequestMapping("/company")
public class CompanyController {
private Logger log = LoggerFactory.getLogger(CompanyController.class);
#Autowired
private CompanyControllerProxy proxy;
#RequestMapping(path= {"/{name}"}, method= {RequestMethod.GET})
public CompanyDTO companyDetails(#PathParam("from") String name) {
CompanyDTO dto = new CompanyDTO();
dto.setName(name);
dto.setAffiliatedTo("HCL Group Of Companies..");
List<EmployeeDTO> employees = proxy.returnEmployeeList();
log.info("{}",employees);
dto.setEmployees(employees);
return dto;
}
}
feign proxy class to call other service
package com.booter.Company.controller;
import java.util.List;
import org.springframework.cloud.netflix.ribbon.RibbonClient;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import com.booter.Company.dto.EmployeeDTO;
#FeignClient(name="person-service")
#RibbonClient(name="person-service")
public interface CompanyControllerProxy {
#GetMapping("/api/persons")
public List<EmployeeDTO> returnEmployeeList();
}
Bootstrap class
package com.booter.Company;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.openfeign.EnableFeignClients;
#SpringBootApplication
#EnableFeignClients("com.booter.Company.controller")
#EnableDiscoveryClient
public class CompanyApplication {
public static void main(String[] args) {
SpringApplication.run(CompanyApplication.class, args);
}
}
application.properties file::
spring.application.name = company-service
server.port = 8200
eureka.client.serviceUrl.defaultZone=http://localhost:8005/eureka
Log
org.springframework.context.ApplicationContextException: Failed to start bean 'eurekaAutoServiceRegistration'; nested exception is java.lang.NullPointerException
at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:184) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:52) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:356) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:157) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:121) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:885) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.finishRefresh(ServletWebServerApplicationContext.java:161) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553) ~[spring-context-5.0.7.RELEASE.jar:5.0.7.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) [spring-boot-2.0.3.RELEASE.jar:2.0.3.RELEASE]
at com.booter.Company.CompanyApplication.main(CompanyApplication.java:15) [classes/:na]
Hi Yogendra,
The problem was with pom.xml indeed, i was explicitly adding ribbon dependency in pom.xml while it's already been part of eureka client because of this i was getting this problem. after removing the ribbon client from pom.xml everything is fine.

It is indirectly referenced from required .class files

The type org.springframework.dao.InvalidDataAccessApiUsageException cannot be resolved.
It is indirectly referenced from required .class files (error is in a first line of code ).
I have not imported org.springframework.dao.InvalidDataAccessApiUsageExceptionstill it is showing the error.
(Error) /**
*#author Infosys
*Create Date Created on Nov 23, 2011
*Sr.No. Modification Date Modified By Reason
* 1.0 11/28/2011 Vasu Rathore Initial code for P8344b
*/
package com.aetna.channel.catsIntake.common.util.sp;
import java.sql.Types;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.jdbc.core.SqlOutParameter;
import org.springframework.jdbc.core.SqlParameter;
import org.springframework.jdbc.object.StoredProcedure;
import com.aetna.channel.catsIntake.caseId.spAdapters.ComplaintAndAppealCaseIdGenSP;
import com.aetna.channel.catsIntake.common.exceptions.CatsControllerException;
import com.aetna.channel.catsIntake.common.exceptions.CatsDatabaseException;
import com.aetna.channel.catsIntake.common.exceptions.CatsExceptionConstants;
import com.aetna.channel.catsIntake.common.exceptions.CatsIntakeSvcDAOException;
import com.aetna.channel.catsIntake.common.exceptions.CatsInvalidInputException;
import com.aetna.channel.catsIntake.common.exceptions.CatsNoDataFoundExeception;
import com.aetna.channel.catsIntake.common.util.dao.CatsLookUpDao;
org.springframework.dao.InvalidDataAccessApiUsageException is contained in spring-tx-<version>.jar so you are probably missing that dependency.
I got the same error in Spring project and I added the spring jdbc dependency which resolved my issue.
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>

Resources