Tag Archives: spring boot

Unable to read meta data for class

From: http://www.infoq.live/links, original author: Chen, wei

    problem description

Unable to read meta-data for class
Unable to read meta-data for class
Unable to read meta-data for class
Unable to read meta-data for class
Locate

    analysis custom starter in spring. The factories configure multiple configuration, need each other to interval \

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    cn.xxx.xxx.secret.SecretAutoConfiguration,
    cn.xxx.xxx.secret.modules.cors.WebMvcConfiguration
    

    Correct configuration:

    org.springframework.boot.autoconfigure.EnableAutoConfiguration=\
    cn.xxx.xxx.secret.SecretAutoConfiguration,\
    cn.xxx.xxx.secret.modules.cors.WebMvcConfiguration
    

An error was reported when springboot connected to redis Servlet.service () for servlet [dispatcherServlet] in context with path [] threw e

Made a day, finally 11 o ‘clock more than solved, record once. SerializationException: Cannot SerializationException: Cannot SerializationException: Cannot SerializationException: Cannot SerializationException: Cannot SerializationException: Cannot SerializationException: Cannot SerializationException: Cannot SerializationException:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.io.NotSerializableException: com.wanghaixin.springboot.model.Student] with root cause
Solution:
NotSerializable is not serialized objects, object Article cannot be serialized therefore appeared this problem.
JavaBeans to cache must implement the Serializable interface, because Spring serializes objects before storing them in Redis
For this exception, just modify the corresponding JavaBean object, mine is Student

public class Student implements Serializable 

Spring boot project running error: Servlet.service () for servlet [dispatcherServlet] threw exception

spring boot
spring boot
spring boot
spring boot
spring boot
spring boot
Error output from console:

2020-06-29 12:25:44.780 ERROR 1968 --- [nio-8080-exec-4] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] threw exception

java.lang.StackOverflowError: null
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at org.apache.catalina.core.ApplicationHttpRequest.getSession(ApplicationHttpRequest.java:583) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	at javax.servlet.http.HttpServletRequestWrapper.getSession(HttpServletRequestWrapper.java:244) ~[tomcat-embed-core-9.0.36.jar:9.0.36]
	

: The @Autowired annotation is not added to the implementation class in the Service layer. This will cause the implementation class to lack dependencies. An error will occur if the dependencies cannot be found after the project is started.
Original code:

   private EmployeeDao employeeDao;

Modified code after adding annotations:

 @Autowired
   private EmployeeDao employeeDao;

The problem is resolved by adding the @Autowired annotation.

Unknown error in POM file of springboot project

SpringBoot project POM file is Unknown error

The Maven Jar plugin was updated from 3.1.1 to 3.1.2 from Spring Boot 2.1.5. Release
Solution: Downgrade the Maven JAR plug-in to 3.1.1 and add the following configuration in the POM file properties

<maven-jar-plugin.version>3.1.1</maven-jar-plugin.version>

 
The following figure

 
Reference: https://bugs.eclipse.org/bugs/show_bug.cgi?id=547340
 

About content type ‘multipart / form data…’ not support

Project Scenario:
on using springcloud, the gateway jump specifies that the service displays an error message


Problem description:

Content type 'multipart/form-data;boundary=----WebKitFormBoundaryek7Ljn5odm2QALlC;charset=UTF-8' not supported

Reason analysis:
this is because the requested parameter is content-type:multipart/form-data, which is submitted as a form. Therefore, the problem occurs on the parameter, and the annotation on the parameter can be removed (it only needs to be in the parameter form of springmvc)

Resttemplate Chinese garbled problem – available

RestTemplate Chinese garbled code problem
Source code to see the cause of Chinese code solution

Causes the RestTemplate to receive parameters in the request response body with scrambled Chinese characters.
Source code to see the Reason for Chinese scrambled code


to take a closer look at the initialization parameter in the figure above, the default value of this parameter is as shown in the figure below.

you should know the cause of this problem and the solution. [after the RestTemplate is initialized, we will assign and modify it to the utf-8 code we need]
The solution
The SpringBoot project takes the following approach

@Configuration
public class RestTemplateConfig {
    @Bean
    public RestTemplate restTemplate(){
        RestTemplate restTemplate = new RestTemplate(factory);
        restTemplate.getMessageConverters().set(1, new StringHttpMessageConverter(StandardCharsets.UTF_8));
        return restTemplate;
    }
  }

Realization of springboot authorization verification technology based on JWT

The JWT token permission authentication technology based on Springboot is simply implemented
JWT profile
Json Web Token (JWT) : Json network Token, an open standard based on Json ((RFC 7519) for passing declarations between network application environments. JWT is a lightweight, secure, cross-platform transport format that defines a compact, self-contained way to communicate between two parties using JSON objects to securely transfer information. This information is reliable because of the digital signature.
Implementation steps:
Environmental spring boot
1. Add JWT dependency

 <dependency>
            <groupId>com.auth0</groupId>
            <artifactId>java-jwt</artifactId>
            <version>3.8.1</version>
        </dependency>
        <dependency>
            <groupId>io.jsonwebtoken</groupId>
            <artifactId>jjwt</artifactId>
            <version>0.9.1</version>
        </dependency>

2. Create annotation package </h6 b> under SRC
New custom annotation class JwtToken

package com.qf.tyleryue_one.annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;


@Target({ElementType.METHOD,ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface JwtToken {
}

3. Create utils package </h6 b> under SRC
Create a new custom JwtUtils utility class

package com.qf.tyleryue_one.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import jdk.internal.org.objectweb.asm.TypeReference;

import java.util.Date;


public class JwtUtils {
    private final static long EXPIRE_TIME=5*60*1000;
    private final static String SECRECT="Tyler_Yue_key";
    public  static  String sign(String userId){
        Date exipre_date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        JWTCreator.Builder builder = JWT.create();
        builder.withAudience(userId);
        builder.withExpiresAt(exipre_date);
        Algorithm algorithm = Algorithm.HMAC256(SECRECT);
        String sign = builder.sign(algorithm);
        return  sign;
    }

    public  static boolean verifyToken(String token){

        try {
            Algorithm algorithm = Algorithm.HMAC256(SECRECT);
            JWTVerifier build = JWT.require(algorithm).build();
            return  true;
        } catch (Exception e) {
            throw  new RuntimeException("Out of date");
        }
      
    }
}

4. Create new vo package under SRC
Encapsulates an object that returns the user’s token

package com.qf.tyleryue_one.vo;

import com.alibaba.druid.filter.AutoLoad;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;


@Data
@AllArgsConstructor
@NoArgsConstructor
public class TokenVo {
    private  String usernaem;
    private String token;
}

5. Example of controller layer user login business login with token </h6 b>

package com.qf.tyleryue_one.controller;

import com.qf.tyleryue_one.entity.VueUser;
import com.qf.tyleryue_one.service.VueUserService;
import com.qf.tyleryue_one.utils.JwtUtils;
import com.qf.tyleryue_one.vo.Msg;
import com.qf.tyleryue_one.vo.TokenVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.UUID;


@Controller
public class VueUserController {
    @Autowired
    private VueUserService vueUserService;

    @RequestMapping(value = "/dealLogin",method = RequestMethod.POST)
    @CrossOrigin
    @ResponseBody
    public Msg login(@RequestBody VueUser vueUser){
        VueUser vueUser1 = vueUserService.selectByUsername(vueUser.getUsername());

        if (vueUser1!=null){
            if (vueUser1.getPassword().equals(vueUser.getPassword())){
                String userid = UUID.randomUUID().toString();
                String token = JwtUtils.sign(userid);
                TokenVo tokenVo = new TokenVo(vueUser.getUsername(), token);
                return new Msg(200,"Logined",tokenVo);

            }else {
                return  new Msg(403,"password wrong",null);
            }
        }else {
            return new Msg(403,"not exsit",null);
        }
    }
}

</ div>

Field userrepository in com.example.demo2.service.imp.UserServiceImp required a bean of type ‘com.ex

Spring Boot projects may encounter classes in the DAO layer that cannot be injected, as indicated below

Field XXXXXpository in required a bean of type that could not be found.

The injection point has the following annotations:
	- @org.springframework.beans.factory.annotation.Autowired(required=true)


My solution for my project is to add @ComponentScan(basePackages = {” package name “}) to the startup class. This annotation allows the application to scan the configuration under dao at a specified location. The package name should be written to the package containing mapper, starting from the first package in the Java file. Such as: com. Example. Demo2. Dao

Elasticsearch in Spring uses Spel to dynamically create Index of Documet class

1 Usage Scenario
In some projects, the index of ES needs to be dynamically generated according to the conditions in the program to achieve the purpose of data collation. For example, a system log with a large amount of data needs to be indexed, so index needs to be generated dynamically.
2 Spel generates Index dynamically
Here USES the spring - data - elasticsearch </ code> ElasticsearchRestTemplate </ code> es operation, version for 3.2.0.

<dependency>
	<groupId>org.springframework.data</groupId>
	<artifactId>spring-data-elasticsearch</artifactId>
	<version>3.2.0.RELEASE</version>
</dependency>

You can specify the static IndexName when identifying POJO objects using the @document annotation.

@Document(indexName = "indexName", type = "logger")

But how do you dynamically generate an index?So let’s say Spel.
Spel full name is Spring Expression Language, is a Spring Expression Language, function is very powerful, official website.
Using Spel, you can call the Bean’s methods through an expression in the annotation to assign values to parameters.
Therefore, the idea of dynamic generation is to create an index generator and call the generator method in @ducument to assign the attribute indexName.
Examples of generators are as follows:

@Component("indexNameGenerator")
public class IndexNameGenerator {
    public String commonIndex() {
        String date = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
        return "collectlog_" + date;
    }
}

An instance of the Document class is as follows:

@NoArgsConstructor
@Data
@Document(indexName = "#{@indexNameGenerator.commonIndex()}", type = "logger")
public class ESDocument {
    @Field(analyzer = "ik_max_word", searchAnalyzer = "ik_max_word")
    private String content;
    private String cluster;
    private long date = LocalDateTime.now().toInstant(ZoneOffset.ofHours(8)).toEpochMilli();
    private String path;
    private String ip;
    private String level;
}

As you can see, in the @ the Document </ code> annotation, call the indexNameGenerator.com monIndex () </ code>, the method to obtain the Index of every day.
this method is called every time new data is added.
3. Some notes
Note that Spel USES context to get the corresponding Bean Resolver. If the project is running and an exception is reported,

org.springframework.expression.spel.SpelEvaluationException: 
EL1057E: No bean resolver registered in the context to resolve access to bean 'indexNameGenerator'

This reason is mainly caused by problems with the spring context used in Spel, you can break to the SpelExpression#getValue method debugging problem.

org.springframework.expression.spel.standard.SpelExpression#getValue(org.springframework.expression.EvaluationContext, java.lang.Class<T>) 

When used in ES, if is to manually create the ElasticsearchRestTemplate </ code>, must be set when creating the instance of ElasticsearchConverter </ code>, or you will quote the exception.
ElasticsearchConverter can use the generated Bean in springboot autoconfig, in which the correct ApplicationContext has been injected. The example is as follows:

@EnableConfigurationProperties(ESProperties.class)
@Service("elasticSearchHandlerFactory")
public class ElasticSearchHandlerFactory {
    @Resource
    ESProperties esProperties;

    @Resource
    ElasticsearchConverter elasticsearchConverter;

    public ElasticsearchRestTemplate getHandler() {
        ESProperties.DbConfig dbConfig = esProperties.getDbList().get("c1");
        final ClientConfiguration configuration = ClientConfiguration.builder()
                .connectedTo(dbConfig.getHostAndPort())
                .withBasicAuth(dbConfig.getUsername(), dbConfig.getPassword())
                .build();
        RestHighLevelClient client = RestClients.create(configuration).rest();
        return new ElasticsearchRestTemplate(client, elasticsearchConverter);
    }
}

The above content is a personal learning summary, if there is any improper, welcome to correct in the comments