Tag Archives: spring boot

Springboot mybatis Integrate Error: Invalid bound statement (not found): com…DepartmentMapper.save

Error message:

org.apache.ibatis.binding.BindingException: Invalid bound statement (not found): com.qf.java2107.springboot.mapper.DepartmentMapper.save

	at org.apache.ibatis.binding.MapperMethod$SqlCommand.<init>(MapperMethod.java:235)
	at org.apache.ibatis.binding.MapperMethod.<init>(MapperMethod.java:53)
	at org.apache.ibatis.binding.MapperProxy.lambda$cachedInvoker$0(MapperProxy.java:115)
	at java.util.concurrent.ConcurrentHashMap.computeIfAbsent(ConcurrentHashMap.java:1660)
	at org.apache.ibatis.binding.MapperProxy.cachedInvoker(MapperProxy.java:102)
	at org.apache.ibatis.binding.MapperProxy.invoke(MapperProxy.java:85)
	at com.sun.proxy.$Proxy74.save(Unknown Source)
	at com.qf.java2107.springboot.SpringbootDemo01QuickApplicationTests.saveTest(SpringbootDemo01QuickApplicationTests.java:23)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.lang.reflect.Method.invoke(Method.java:498)
	at org.junit.platform.commons.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:725)
	at org.junit.jupiter.engine.execution.MethodInvocation.proceed(MethodInvocation.java:60)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$ValidatingInvocation.proceed(InvocationInterceptorChain.java:131)
	at org.junit.jupiter.engine.extension.TimeoutExtension.intercept(TimeoutExtension.java:149)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestableMethod(TimeoutExtension.java:140)
	at org.junit.jupiter.engine.extension.TimeoutExtension.interceptTestMethod(TimeoutExtension.java:84)
	at org.junit.jupiter.engine.execution.ExecutableInvoker$ReflectiveInterceptorCall.lambda$ofVoidMethod$0(ExecutableInvoker.java:115)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.lambda$invoke$0(ExecutableInvoker.java:105)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain$InterceptedInvocation.proceed(InvocationInterceptorChain.java:106)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.proceed(InvocationInterceptorChain.java:64)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.chainAndInvoke(InvocationInterceptorChain.java:45)
	at org.junit.jupiter.engine.execution.InvocationInterceptorChain.invoke(InvocationInterceptorChain.java:37)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:104)
	at org.junit.jupiter.engine.execution.ExecutableInvoker.invoke(ExecutableInvoker.java:98)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.lambda$invokeTestMethod$7(TestMethodTestDescriptor.java:214)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.invokeTestMethod(TestMethodTestDescriptor.java:210)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:135)
	at org.junit.jupiter.engine.descriptor.TestMethodTestDescriptor.execute(TestMethodTestDescriptor.java:66)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:151)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.util.ArrayList.forEach(ArrayList.java:1259)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at java.util.ArrayList.forEach(ArrayList.java:1259)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.invokeAll(SameThreadHierarchicalTestExecutorService.java:41)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$6(NodeTestTask.java:155)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$8(NodeTestTask.java:141)
	at org.junit.platform.engine.support.hierarchical.Node.around(Node.java:137)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.lambda$executeRecursively$9(NodeTestTask.java:139)
	at org.junit.platform.engine.support.hierarchical.ThrowableCollector.execute(ThrowableCollector.java:73)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.executeRecursively(NodeTestTask.java:138)
	at org.junit.platform.engine.support.hierarchical.NodeTestTask.execute(NodeTestTask.java:95)
	at org.junit.platform.engine.support.hierarchical.SameThreadHierarchicalTestExecutorService.submit(SameThreadHierarchicalTestExecutorService.java:35)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestExecutor.execute(HierarchicalTestExecutor.java:57)
	at org.junit.platform.engine.support.hierarchical.HierarchicalTestEngine.execute(HierarchicalTestEngine.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:107)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:88)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.lambda$execute$0(EngineExecutionOrchestrator.java:54)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.withInterceptedStreams(EngineExecutionOrchestrator.java:67)
	at org.junit.platform.launcher.core.EngineExecutionOrchestrator.execute(EngineExecutionOrchestrator.java:52)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:114)
	at org.junit.platform.launcher.core.DefaultLauncher.execute(DefaultLauncher.java:86)
	at org.junit.platform.launcher.core.DefaultLauncherSession$DelegatingLauncher.execute(DefaultLauncherSession.java:86)
	at org.junit.platform.launcher.core.SessionPerRequestLauncher.execute(SessionPerRequestLauncher.java:53)
	at com.intellij.junit5.JUnit5IdeaTestRunner.startRunnerWithArgs(JUnit5IdeaTestRunner.java:69)
	at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33)
	at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230)
	at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)

Error reason: the namespace of mapper mapping file is written incorrectly

<mapper namespace="com.qf.java2107.springboot.demo02.mapper.DepartmentMapper">

After modification, it is successful

<mapper namespace="com.qf.java2107.springboot.mapper.DepartmentMapper">

[Solved] Springboot project Create to start Error: APPLICATION FAILED TO START

 

Description:
Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.
Reason: Failed to determine a suitable driver class
Action:
Consider the following:
If you want an embedded database (H2, HSQL or Derby), please put it on the classpath.
If you have database settings to be loaded from a particular profile you may need to activate it (no profiles are currently active).
Process finished with exit code 1

Reason:
Spring boot loads the org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration class by default, after introducing mybatis-spring-boot-starter in the pom. DataSourceAutoConfiguration class uses the @Configuration annotation to inject the dataSource bean into spring because there is no configuration information about the dataSource in the project, so when spring creates the dataSource bean due to the lack of relevant information it will report an error.

Solution:
Add attribute @SpringBootApplication(exclude = DataSourceAutoConfiguration.class) to the Spring boot boot boot class to prevent Spring boot from automatically injecting the dataSource

[Solved] spingboot Error: I/O error on POST request for “9411/api/v2/spans“: connect timed out

Springboot error I/O error on post request for“ http://10.10.195.199:9411/api/v2/spans “: connect timed out; nested exception is java.net.SocketTimeoutException: connect timed out

Problem background solution experience Lyric: a sack of love and happiness

Problem background

When using Zipkin, the following error occurs when accessing the URL

2022-01-11 11:22:35.554  WARN [service-one,,,] 40592 --- [ender@131ff6fa}] z.r.AsyncReporter$BoundedAsyncReporter   : Spans were dropped due to exceptions. All subsequent errors will be logged at FINE level.
2022-01-11 11:22:35.557  WARN [service-one,,,] 40592 --- [ender@131ff6fa}] z.r.AsyncReporter$BoundedAsyncReporter   : Dropped 1 spans due to ResourceAccessException(I/O error on POST request for "http://10.10.195.199:9411/api/v2/spans": connect timed out; nested exception is java.net.SocketTimeoutException: connect timed out)

org.springframework.web.client.ResourceAccessException: I/O error on POST request for "http://10.10.195.199:9411/api/v2/spans": connect timed out; nested exception is java.net.SocketTimeoutException: connect timed out
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:751) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.cloud.sleuth.zipkin2.sender.ZipkinRestTemplateWrapper.doExecute(ZipkinRestTemplateSenderConfiguration.java:228) ~[spring-cloud-sleuth-zipkin-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:644) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.cloud.sleuth.zipkin2.sender.RestTemplateSender.post(RestTemplateSender.java:129) ~[spring-cloud-sleuth-zipkin-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.cloud.sleuth.zipkin2.sender.RestTemplateSender$HttpPostCall.doExecute(RestTemplateSender.java:142) ~[spring-cloud-sleuth-zipkin-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at org.springframework.cloud.sleuth.zipkin2.sender.RestTemplateSender$HttpPostCall.doExecute(RestTemplateSender.java:132) ~[spring-cloud-sleuth-zipkin-2.2.0.RELEASE.jar:2.2.0.RELEASE]
	at zipkin2.Call$Base.execute(Call.java:380) ~[zipkin-2.19.0.jar:na]
	at zipkin2.reporter.AsyncReporter$BoundedAsyncReporter.flush(AsyncReporter.java:285) ~[zipkin-reporter-2.11.0.jar:na]
	at zipkin2.reporter.AsyncReporter$Flusher.run(AsyncReporter.java:354) [zipkin-reporter-2.11.0.jar:na]
	at java.lang.Thread.run(Thread.java:748) [na:1.8.0_172]
Caused by: java.net.SocketTimeoutException: connect timed out
	at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) ~[na:1.8.0_172]
	at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) ~[na:1.8.0_172]
	at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350) ~[na:1.8.0_172]
	at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206) ~[na:1.8.0_172]
	at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188) ~[na:1.8.0_172]
	at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172) ~[na:1.8.0_172]
	at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392) ~[na:1.8.0_172]
	at java.net.Socket.connect(Socket.java:589) ~[na:1.8.0_172]
	at sun.net.NetworkClient.doConnect(NetworkClient.java:175) ~[na:1.8.0_172]
	at sun.net.www.http.HttpClient.openServer(HttpClient.java:463) ~[na:1.8.0_172]
	at sun.net.www.http.HttpClient.openServer(HttpClient.java:558) ~[na:1.8.0_172]
	at sun.net.www.http.HttpClient.<init>(HttpClient.java:242) ~[na:1.8.0_172]
	at sun.net.www.http.HttpClient.New(HttpClient.java:339) ~[na:1.8.0_172]
	at sun.net.www.http.HttpClient.New(HttpClient.java:357) ~[na:1.8.0_172]
	at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(HttpURLConnection.java:1220) ~[na:1.8.0_172]
	at sun.net.www.protocol.http.HttpURLConnection.plainConnect0(HttpURLConnection.java:1156) ~[na:1.8.0_172]
	at sun.net.www.protocol.http.HttpURLConnection.plainConnect(HttpURLConnection.java:1050) ~[na:1.8.0_172]
	at sun.net.www.protocol.http.HttpURLConnection.connect(HttpURLConnection.java:984) ~[na:1.8.0_172]
	at org.springframework.http.client.SimpleBufferingClientHttpRequest.executeInternal(SimpleBufferingClientHttpRequest.java:76) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.http.client.AbstractBufferingClientHttpRequest.executeInternal(AbstractBufferingClientHttpRequest.java:48) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.http.client.AbstractClientHttpRequest.execute(AbstractClientHttpRequest.java:53) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:742) ~[spring-web-5.2.1.RELEASE.jar:5.2.1.RELEASE]
	... 9 common frames omitted

Solution

1. The firewall is not turned off

systemctl stop firewalld

Experience

1. I was tired of finding the problem. Another time, I just introduced Zipkin dependency, which was not used, and a similar error occurred.

Jjwt error: ERROR 9856 — [nio-8083-exec-2] o.a.c.c. [. [. [. [/]. [dispatch server]

**

Solve jjwt generation error

**
recently, when learning springboot + JWT + Vue, an error occurred while generating JWT. The error code is as follows:

2022-01-07 11:17:32.335 ERROR 9856 --- [nio-8083-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Filter execution threw an exception] with root cause

java.lang.ClassNotFoundException: javax.xml.bind.DatatypeConverter
	at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:641) ~[na:na]
	at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:188) ~[na:na]
	at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:520) ~[na:na]
	at io.jsonwebtoken.impl.Base64Codec.decode(Base64Codec.java:26) ~[jjwt-0.9.1.jar:0.9.1]
	at io.jsonwebtoken.impl.DefaultJwtBuilder.signWith(DefaultJwtBuilder.java:99) ~[jjwt-0.9.1.jar:0.9.1]
	at com.okwind.utils.JwtUtils.generateToken(JwtUtils.java:31) ~[classes/:na]
	at com.okwind.security.LoginSuccessHandler.onAuthenticationSuccess(LoginSuccessHandler.java:32) ~[classes/:na]

Analysis error code: at com okwind.utils.JwtUtils. Generatetoken (jwtutils.Java: 31) ~ [classes/: Na] knows that the error occurred in jwtutils Generatetoken (jwtutils.Java: 31) is on line 31 of the tool class.

 26        return Jwts.builder()
 27               .setHeaderParam("typ", "JWT")
 28               .setSubject(username)
 29               .setIssuedAt(nowDate)
 30               .setExpiration(expireDate)
 31               .signWith(SignatureAlgorithm.HS256, app_secret)
 32               .compact();

It means that an exception occurred in generateToken() and it is related to SignatureAlgorithm.HS256.
after analysis, it is referenced:

        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

jjwt version 0.91 is not supported for new JDK versions. There are two solutions.

Method 1: jdk drops to below 11.
Method 2: keep the jdk version unchanged from the higher version and introduce in pom.xml.

<dependency>
    <groupId>io.jsonwebtoken</groupId>
    <artifactId>jjwt</artifactId>
    <version>0.9.1</version>
</dependency>
<dependency>
    <groupId>javax.xml.bind</groupId>
    <artifactId>jaxb-api</artifactId>
    <version>2.4.0-b180830.0359</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-impl</artifactId>
    <version>3.0.0-M4</version>
</dependency>
<dependency>
    <groupId>com.sun.xml.bind</groupId>
    <artifactId>jaxb-core</artifactId>
    <version>3.0.0-M4</version>
</dependency>
<dependency>
    <groupId>javax.activation</groupId>
    <artifactId>activation</artifactId>
    <version>1.1.1</version>
</dependency>

So far, the problem is solved.

Error resolving template [index], template might not exist

Problem: error resolving template [index], template may not exist
Solution:
1. Check the project structure first and check whether the location of the static resource file is misplaced

2. Check if the thymeleaf dependency in pom.xml is imported correctly
At first, I only imported the following dependencies, but it reported an error

  <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

3. Change to the following, just download it again

<!--        thymeleaf -->
        <dependency>
            <groupId>org.thymeleaf</groupId>
            <artifactId>thymeleaf-spring5</artifactId>
        </dependency>
        <dependency>
            <groupId>org.thymeleaf.extras</groupId>
            <artifactId>thymeleaf-extras-java8time</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-thymeleaf</artifactId>
        </dependency>

Springboot startup error: err config is disabled command (Redis Disables Config command)

1. Background description

The project belongs to spring boot, which is always normal. Due to the recent security activity disabling redis’s config command, an error is reported when the project is restarted:

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'enableRedisKeyspaceNotificationsInitializer' defined in class path resource [org/springframework/boot/autoconfigure/session/RedisSessionConfiguration$SpringBootRedisHttpSessionConfiguration.class]: Invocation of init method failed; 
nested exception is org.springframework.data.redis.connection.ClusterCommandExecutionFailureException: ERR config is disabled command; 
nested exception is redis.clients.jedis.exceptions.JedisDataException: ERR config is disabled command; 
nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: ERR config is disabled command; 
nested exception is redis.clients.jedis.exceptions.JedisDataException: ERR config is disabled command

2. Analysis

Check the source code of redishttpsessionconfiguration class (as shown below), and find the input parameter to enable the keyspace notifications function: configurereredisaction.configurereredisaction accepts the injection. The default is new configurenotifykeyspaceeventsaction() in the constructor. Looking at the source code of this class (not posted here), we find that this class is used to configure the “notify keyspace events” function. Then, redis’s config command will be used in the static internal class enablererediskeyspacenotificationsinitializer, Since the config command is disabled, the above exception is reported.

Look at the post-processing condition if (this.configure! =configurereredisaction.no_op) in the static internal class. The solution is obvious here.

The solution is to inject configurereredisaction.NO_OP, do not receive the default configurenotifykeyspaceeventsaction.configureRedisAction.NO_op itself does not do any processing.

private ConfigureRedisAction configureRedisAction;

......

public RedisHttpSessionConfiguration() {
        this.redisFlushMode = RedisFlushMode.ON_SAVE;
        this.cleanupCron = "0 * * * * *";
        this.configureRedisAction = new ConfigureNotifyKeyspaceEventsAction();
    }

......

@Autowired(
        required = false
    )
    public void setConfigureRedisAction(ConfigureRedisAction configureRedisAction) {
        this.configureRedisAction = configureRedisAction;
    }

......

@Bean
    public InitializingBean enableRedisKeyspaceNotificationsInitializer() {
        return new RedisHttpSessionConfiguration.EnableRedisKeyspaceNotificationsInitializer(this.redisConnectionFactory, this.configureRedisAction);
    }
......

static class EnableRedisKeyspaceNotificationsInitializer implements InitializingBean {
        private final RedisConnectionFactory connectionFactory;
        private ConfigureRedisAction configure;

        EnableRedisKeyspaceNotificationsInitializer(RedisConnectionFactory connectionFactory, ConfigureRedisAction configure) {
            this.connectionFactory = connectionFactory;
            this.configure = configure;
        }

        public void afterPropertiesSet() throws Exception {
            if (this.configure != ConfigureRedisAction.NO_OP) {
                RedisConnection connection = this.connectionFactory.getConnection();

                try {
                    this.configure.configure(connection);
                } finally {
                    try {
                        connection.close();
                    } catch (Exception var8) {
                        LogFactory.getLog(this.getClass()).error("Error closing RedisConnection", var8);
                    }

                }

            }
        }
    }

3. Solutions

Inject the default object configurereredisaction.NO_OP, add a configuration item switch to keep unchanged and respond to changes.

package com.abc.test.config;

import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.session.data.redis.config.ConfigureRedisAction;

/**
 * After disabling Redis' config command.
 * Here when the configuration file redis.disableConfig=true inject ConfigureRedisAction.NO_OP to solve the problem, otherwise it is handled by default
 * @author test
 * @version 1.0
 * @date 2021/12/29 15:44
 */
@Configuration
@ConditionalOnProperty(value = "redis.disableConfig", havingValue = "true")
public class HttpSessionConfig {

    @Bean
    public static ConfigureRedisAction configureRedisAction(){
        return ConfigureRedisAction.NO_OP;
    }
}

Time is pressing, over!

[Solved] The Bean Validation API is on the classpath but no implementation could be found

Question

When starting the springboot service, the service reports an error. The specific error information is as follows:

Description:
The Bean Validation API is on the classpath but no implementation could be found
Action:
Add an implementation, such as Hibernate Validator, to the classpath

reason:

Dependency in POM

<dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>7.0.0.Final</version>
        </dependency>

And

<dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
            <version>2.2.6.RELEASE</version>
        </dependency>

Conflict.

Solution:

The dependency is deleted because it is not used in the service

<dependency>
            <groupId>org.hibernate.validator</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>7.0.0.Final</version>
        </dependency>

Restart the service normally.

[Solved] Springboot uses redis to add LocaldateTime Java 8 error

To store an object in redis, you need to serialize the object. If a field is of localdatetime type, an error will appear

com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Java 8 date/time type `java.time.LocalDateTime` not supported by default: add Module "com.fasterxml.jackson.datatype:jackson-datatype-jsr310" to enable handling (through reference chain: com.gd.base.vo.redis.RedisSysUser["Corresponding fields"])

The program needs to deserialize the data in redis. The deserializer I use here is the following:

@Configuration
@EnableCaching//Allow us to use the cache
public class RedisConfig {
    /**
     * Cache expiration time (seconds)
     */
    public static final long CACHE_EXPIRE_SECEND = 3600 * 2;

    @Bean // At this point, load our redisTemplate into the context of our spring, applicationContext
    public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
        //1. Initialize a redisTemplate
        RedisTemplate<String,Object> redisTemplate=new RedisTemplate<String,Object>();
        //2. Serial words (generally used for key values)
        RedisSerializer<String> redisSerializer=new StringRedisSerializer();
        //3. Introduce the json string conversion class (generally used for value processing)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        //3.1 Set the access rights of objectMapper
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //3.2 Specify the serialized input type, that is, store the data in the database to the redis cache according to certain types.
        </objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);// Recently upgraded SpringBoot, found that enableDefaultTyping method expired. You can use the following method instead
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As. WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //4. Create the link
        redisTemplate.setConnectionFactory(factory);
        //4.1 redis key value serialization
        redisTemplate.setKeySerializer(redisSerializer);
        //4.2 value serialization, because most of our values are converted through objects, so use jackson2JsonRedisSerializer
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        // 4.3 Serialization of value, serialization of hashmap
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        return redisTemplate;
    }

    @Bean
    public CacheManager cacheManager(RedisConnectionFactory factory){
        // 1. Serial words (generally used for key values)
        RedisSerializer<String> redisSerializer=new StringRedisSerializer();
        //2. Introduce the json string conversion class (generally used for value processing)
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer=new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper=new ObjectMapper();
        //2.1 Set the access rights of objectMapper
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        //2.2 Specify the serialized input type, that is, store the data in the database to the redis cache according to a certain type.
        </objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);// Recently upgraded SpringBoot, found that enableDefaultTyping method expired. You can use the following method instead
        objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As. WRAPPER_ARRAY);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        //3. Serialization configuration, garbled problem solving and timeliness of our cache
        RedisCacheConfiguration config=RedisCacheConfiguration.defaultCacheConfig().
                entryTtl(Duration.ofSeconds(CACHE_EXPIRE_SECEND)). // Cache timeliness setting
                serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer)). //key serialization
                serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer)). //value serialization
                disableCachingNullValues();//null values are not stored in the cache
        //4. Create the cacheManager link and set the properties
        RedisCacheManager cacheManager= RedisCacheManager.builder(factory).cacheDefaults(config).build();
        return cacheManager;
    }

}

Processing error reports:
① add comments to the corresponding fields

    @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss")
    @JsonDeserialize(using = LocalDateTimeDeserializer.class)
    @JsonSerialize(using = LocalDateTimeSerializer.class)

The error report is gone

Springcloud builds a gateway and starts Error [Solved]

1.Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.

Solution:

           <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-web</artifactId>
                </exclusion>

2. Failed to configure a DataSource: ‘url’ attribute is not specified and no embedded datasource could be configured.

Solution:

             <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-jdbc</artifactId>
                </exclusion>

[Solved] Spring upload file Error: Multipartfile Transferto() reported an error FileNotFoundException

When uploading files, use multipartfile Transferto() saves the file to the local path:

report errors:

java.io.IOException: java.io.FileNotFoundException: C:\Users\XXXXX\AppData\Local\Temp\tomcat. 8350081478984499756.8080\work\Tomcat\localhost\ROOT\app\file\xxxx. Xlsx (the system cannot find the specified path.)

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        File dest = new File(filePath, fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

Cause analysis:

file. When the transferto method is called, it is judged that if it is a relative path, the temp directory is used as the parent directory
so it is saved in the temporary work directory of Tomcat.

Solution:

Use absolute path: filepath.getAbsolutePath()

    @Override
    public String store(MultipartFile file, String fileName) throws IOException {

        String destPath "/app/file/";
        File filePath = new File(destPath);
        
        // Convert to absolute path
        File dest = new File(filePath.getAbsolutePath(), fileName);
        if (!filePath.exists()) {
            filePath.mkdirs();
        }
        try {
            file.transferTo(dest);
            log.info("file save success");
        } catch (IOException e) {
            log.error("File upload Error: ", e);
            throw e;
        }
        return dest.getCanonicalPath();
    }

Supplement:

You can also file Getbytes() gets the byte array, or file Getinputstream() performs stream data operation and writes it to disk.

Access to uploaded files

spring:
	resources:
    	static-locations: file:/app/file/  #Access external system resources and map the files in this directory to the system

or

import java.io.File;
import java.util.concurrent.TimeUnit;

import org.springframework.context.annotation.Configuration;
import org.springframework.http.CacheControl;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        String absolutePath = new File("/app/file/").getAbsolutePath();
        
        registry.addResourceHandler("/upload/**") // External Access Addresses
                .addResourceLocations("file:" + absolutePath)// SpringBoot needs to add the file protocol prefix
                .setCacheControl(CacheControl.maxAge(30, TimeUnit.MINUTES));// set the browser cache
    }
}

[Solved] Feign Error: -‘oauth-client.FeignClientSpecification‘ could not be registered

environment

<spring-boot.version>2.5.3</spring-boot.version>
<spring-cloud.version>2020.0.3</spring-cloud.version>
<spring-cloud-alibaba.version>2021.1</spring-cloud-alibaba.version>

report errors

Errors are reported during project startup, as follows:

2021-12-22 16:55:56.766  WARN 21922 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.support.BeanDefinitionOverrideException: Invalid bean definition with name 'oauth-client.FeignClientSpecification' defined in null: Cannot register bean definition [Generic bean: class [org.springframework.cloud.openfeign.FeignClientSpecification]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] for bean 'oauth-client.FeignClientSpecification': There is already [Generic bean: class [org.springframework.cloud.openfeign.FeignClientSpecification]; scope=; abstract=false; lazyInit=null; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] bound.
2021-12-22 16:55:56.776  INFO 21922 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2021-12-22 16:55:56.799 ERROR 21922 --- [           main] o.s.b.d.LoggingFailureAnalysisReporter   : 

***************************
APPLICATION FAILED TO START
***************************

Description:

The bean 'xxx-client.FeignClientSpecification' could not be registered. A bean with that name has already been defined and overriding is disabled.

Action:

Consider renaming one of the beans or enabling overriding by setting spring.main.allow-bean-definition-overriding=true

reason

Multiple interfaces in a project use @ feignclient to call the same service, which means that a service can only be used once with @ feignclient.

Solution:

1) Distinguish with ContextID

But I don’t know why it didn’t work

@FeignClient(value = “xxx-server”, contextId = “oauth-client”)
public interface OAuthClientFeignClient {
@GetMapping("/api/v1/oauth-clients/{clientId}")
Result<SysOauthClient> getOAuthClientById(@PathVariable String clientId);
}

2) Add the following code to the application.properties file.

#Allow the existence of multiple Feign calls to the same Service interface
spring.main.allow-bean-definition-overriding=true

3) Add the following code to the application.yml file.

spring:
  main:
    #Allow the existence of multiple Feign calls to the same Service interface
    allow-bean-definition-overriding: true
        The above code enables multiple interfaces to call the same service using @FeignClient.