Eureka and Feign MicroWebservice failing to startup - microservices

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.

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

Spring Cloud Task Scheduling Context Closed

When I run my task without the CommandLineRunner implemented and add the #Scheduled annotation it appears the context is being closed. How can I keep the context open so the #Scheduled can run properly?
DataTransferTask.java
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DataTransferTask {
public static void main(String[] args) {
SpringApplication.run(DataTransferTask.class, args);
}
}
DataTransferRunner.java
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.task.configuration.EnableTask;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.util.List;
#Component
#EnableTask
#EnableScheduling
public class DataTransferRunner {
#Autowired
public DataTransferRunner() {
}
#Scheduled(fixedRateString = "${job_concurrency.fixed-rate}")
public void run() throws Exception {
System.out.println("I started running");
}
}
Here is the exception I keep getting
Caused by: java.lang.IllegalStateException: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext#21526f6c has been closed already
at org.springframework.context.support.AbstractApplicationContext.assertBeanFactoryActive(AbstractApplicationContext.java:1065) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBeanNamesForType(AbstractApplicationContext.java:1176) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.cloud.task.batch.configuration.TaskBatchExecutionListenerBeanPostProcessor.postProcessAfterInitialization(TaskBatchExecutionListenerBeanPostProcessor.java:59) ~[spring-cloud-task-batch-1.2.0.RELEASE.jar:1.2.0.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsAfterInitialization(AbstractAutowireCapableBeanFactory.java:423) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1633) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 73 common frames omitted
Since you have #EnableTask, spring will close the context once everything is done running. From the code it looks like you are not running anything explicitly so spring is closing the context before your #Schedule() annotation kicks in.
The fix for that is to tell spring to not close the context at all with spring.cloud.task.closecontext_enable=false. This will keep the context open for your scheduled task.
Some documentation here: https://docs.spring.io/spring-cloud-task/docs/1.2.2.RELEASE/reference/htmlsingle/#features-lifecycle
One more note about the property. In the documentation it says closecontext_enable but after inspecting the logs and the jar, that property has been deprecated and replaced by close_context_enabled.

Spring Cache Abstraction VS interfaces VS key param ("Null key returned for cache operation" error)

While implementing, I came across a problem with Spring Cache Abstraction VS interfaces.
Lets say I have the following interface:
package com.example.cache;
public interface IAddItMethod
{
Integer addIt(String key);
}
And the two following implementations:
package com.example.cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
#Component
public class MethodImplOne implements IAddItMethod
{
#Override
#Cacheable(value="integersPlusOne", key="#keyOne")
public Integer addIt(String keyOne)
{
return new Integer(Integer.parseInt(keyOne) + 1);
}
}
.
package com.example.cache;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Component;
#Component
public class MethodImplTwo implements IAddItMethod
{
#Override
#Cacheable(value="integersPlusTwo", key="#keyTwo")
public Integer addIt(String keyTwo)
{
return new Integer(Integer.parseInt(keyTwo) + 2);
}
}
Note that the IAddItMethod is not the one specifying #Cacheable. We could have other implementation (ex MethodImplThree) without the #Cacheable annotation.
We’ve got a simple beans.xml with:
context:component-scan base-package="com.example.cache"
Adding to that, two jUnit test cases:
package com.example.cache;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:beans.xml"})
public class MethodImplOneTest
{
#Autowired
#Qualifier("methodImplOne")
private IAddItMethod classUnderTest;
#Test
public void testInit()
{
int number = 1;
assertEquals(new Integer(number + 1), classUnderTest.addIt("" + number));
}
}
.
package com.example.cache;
import static org.junit.Assert.assertEquals;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
#RunWith(SpringJUnit4ClassRunner.class)
#ContextConfiguration(locations = {"classpath:beans.xml"})
public class MethodImplTwoTest
{
#Autowired
#Qualifier("methodImplTwo")
private IAddItMethod classUnderTest;
#Test
public void testInit()
{
int number = 1;
assertEquals(new Integer(number + 2), classUnderTest.addIt("" + number));
}
}
When I run the tests individually, they succeed.
However, if I run them both together (selecting the package, right-click, run as), the second one (not necessarily MethodImplTwoTest, just the second one running) will fail with the following exception:
java.lang.IllegalArgumentException: Null key returned for cache operation (maybe you are using named params on classes without debug info?) CacheableOperation[public java.lang.Integer com.example.cache.MethodImplOne.addIt(java.lang.String)] caches=[integersPlusOne] | condition='' | key='#keyOne'
at org.springframework.cache.interceptor.CacheAspectSupport.inspectCacheables(CacheAspectSupport.java:297)
at org.springframework.cache.interceptor.CacheAspectSupport.execute(CacheAspectSupport.java:198)
at org.springframework.cache.interceptor.CacheInterceptor.invoke(CacheInterceptor.java:66)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at $Proxy16.addIt(Unknown Source)
at com.example.cache.ITMethodImplOneIntegrationTest.testInit(ITMethodImplOneIntegrationTest.java:26)
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.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:20)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
note: I'm using Eclipse STS 3.0 and the "Add variable attributes to generated class files" is enabled.
IMPORTANT: If I don't specify the "key" in the #Cacheable annotations, it works.
Is there anything I forgot to specify? config? annotations?
Thanks in advance!
My guess is that for jdk proxy the parameter name is fetched from the interface method so it's key and not keyTwo.
update: You can try to use parameter indexes instead
If for some reason the names are not available (ex: no debug
information), the parameter names are also available under the p<#arg>
where #arg stands for the parameter index (starting from 0).
see http://static.springsource.org/spring/docs/3.1.0.M1/spring-framework-reference/html/cache.html#cache-spel-context

Resources