【SpringBoot】Miscellaneous Notes on SpringBoot2.x Knowledge Points

This article is for learning and communication only

Chapter 1 JavaConfig

  1. Why use Spring Boot

    Because of Spring, SpringMVC needs to use a large number of configuration files (xml files)

    You also need to configure various objects, put the used objects into the spring container to use the objects

    Requires knowledge of additional framework configuration rules.

  2. SpringBoot is equivalent to Spring+SpringMVC that does not require configuration files. Commonly used frameworks and third-party libraries are already configured.

    Get it and use it.

  3. SpringBoot has high development efficiency and is much more convenient to use

1.1 JavaConfig

JavaConfig: Using java classes as an alternative to xml configuration files is a pure java way of configuring spring containers. In this java class, you can create java objects, put the objects into the spring container (inject into the container),

Use two annotations:

1) @Configuration: Put it on top of a class, indicating that this class is used as a configuration file.

2) @Bean: Declare the object and inject the object into the container.

例子:
package com.bjpowernode.config;

import com.bjpowernode.vo.Student;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * Configuration:表示当前类是作为配置文件使用的。 就是用来配置容器的
 *       位置:在类的上面
 *
 *  SpringConfig这个类就相当于beans.xml
 */
@Configuration
public class SpringConfig {
    
    

    /**
     * 创建方法,方法的返回值是对象。 在方法的上面加入@Bean
     * 方法的返回值对象就注入到容器中。
     *
     * @Bean: 把对象注入到spring容器中。 作用相当于<bean>
     *
     *     位置:方法的上面
     *
     *     说明:@Bean,不指定对象的名称,默认是方法名是 id
     *
     */
    @Bean
    public Student createStudent(){
    
    
        Student s1  = new Student();
        s1.setName("张三");
        s1.setAge(26);
        s1.setSex("男");
        return s1;
    }


    /***
     * 指定对象在容器中的名称(指定<bean>的id属性)
     * @Bean的name属性,指定对象的名称(id)
     */
    @Bean(name = "lisiStudent")
    public Student makeStudent(){
    
    
        Student s2  = new Student();
        s2.setName("李四");
        s2.setAge(22);
        s2.setSex("男");
        return s2;
    }
}

1.2 @ImporResource

The role of @ImportResource is to import other xml configuration files, which is equal to xml

<import resources="其他配置文件"/>

For example:

@Configuration
@ImportResource(value ={
    
     "classpath:applicationContext.xml","classpath:beans.xml"})
public class SpringConfig {
    
    
}

1.3 @PropertyResource

@PropertyResource: Read the properties property configuration file. Externalized configuration can be achieved using property configuration files,

Provide data outside of program code.

step:

  1. In the resources directory, create a properties file and provide data in the format of k=v
  2. Specify the location of the properties file in PropertyResource
  3. Use @Value(value="${key}")
@Configuration
@ImportResource(value ={
    
     "classpath:applicationContext.xml","classpath:beans.xml"})
@PropertySource(value = "classpath:config.properties")
@ComponentScan(basePackages = "com.bjpowernode.vo")
public class SpringConfig {
    
    
}

Chapter 2 Spring Boot

2.1 Introduction

SpringBoot is a member of Spring, which can simplify the use of Spring and SpringMVC. His core is still the IOC container.

Features:

  • Create stand-alone Spring applications

    Create a spring application

  • Embed Tomcat, Jetty or Undertow directly (no need to deploy WAR files)

    Embedded tomcat, jetty, Undertow

  • Provide opinionated ‘starter’ dependencies to simplify your build configuration

    The starter dependency is provided to simplify the configuration of the application.

    For example, to use the MyBatis framework, you need to configure the MyBatis object SqlSessionFactory and the Dao proxy object in the Spring project

    In the SpringBoot project, add a mybatis-spring-boot-starter dependency in pom.xml

  • Automatically configure Spring and 3rd party libraries whenever possible

    Configure spring and third-party libraries as much as possible. It is called automatic configuration (that is, all objects in spring and third-party libraries are created and placed in the container, so that developers can use them directly)

  • Provide production-ready features such as metrics, health checks, and externalized configuration

    Provides health checks, statistics, externalized configuration

  • Absolutely no code generation and no requirement for XML configuration

    No need to generate code, no need to use xml, do configuration

2.2 Create a Spring Boot project

For the three ways to create a SpringBoot project, please refer to the blog post: 3 ways to create a SpringBoot project - Nuggets (juejin.cn)

2.2.1 The first way, using the initializer provided by Spring, is to create a SpringBoot application with the wizard

Address used: https://start.spring.io

2.2.1 Using a domestic address

https://start.springboot.io

2.3 Use of annotations

@SpringBootApplication
符合注解:由
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan
    
    
1.@SpringBootConfiguration
    
@Configuration
public @interface SpringBootConfiguration {
    
    
    @AliasFor(
        annotation = Configuration.class
    )
    boolean proxyBeanMethods() default true;
}

说明:使用了@SpringBootConfiguration注解标注的类,可以作为配置文件使用的,
    可以使用Bean声明对象,注入到容器

2.@EnableAutoConfiguration

Enable automatic configuration, configure the java object, and inject it into the spring container. For example, the object of mybatis can be created and put into the container

3.@ComponentScan

@ComponentScan 扫描器,找到注解,根据注解的功能创建对象,给属性赋值等等。
默认扫描的包: @ComponentScan所在的类所在的包和子包。
    

2.4 SpringBoot configuration file

Configuration file name: application

The extensions are: properties( k=v) ; yml ( k: v)

Use application.properties, application.yml

Example 1: application.properties setting port and context

#设置端口号
server.port=8082
#设置访问应用上下文路径, contextpath
server.servlet.context-path=/myboot

Example 2: application.yml

server:
  port: 8083
  servlet:
    context-path: /myboot2

2.5 Multi-environment configuration

There are development environment, test environment, and online environment.

Each environment has different configuration information, such as port, upper and lower files, database url, user name, password, etc.

Using multi-environment configuration files, you can easily switch between different configurations.

Usage: create multiple configuration files, name rule: application-environment name.properties(yml)

Create a configuration file for the development environment: application-dev.properties( application-dev.yml )

Create the configuration used by the tester: application-test.properties

2.6 @ConfigurationProperties

@ConfigurationProperties: Map the data of the configuration file to a java object.

Attribute: the content at the beginning of some keys in the prefix configuration file.


@Component
@ConfigurationProperties(prefix = "school")
public class SchoolInfo {
    
    

    private String name;

    private String website;

    private String address;


    public String getName() {
    
    
        return name;
    }

    public void setName(String name) {
    
    
        this.name = name;
    }

    public String getWebsite() {
    
    
        return website;
    }

    public void setWebsite(String website) {
    
    
        this.website = website;
    }

    public String getAddress() {
    
    
        return address;
    }

    public void setAddress(String address) {
    
    
        this.address = address;
    }

    @Override
    public String toString() {
    
    
        return "SchoolInfo{" +
                "name='" + name + '\'' +
                ", website='" + website + '\'' +
                ", address='" + address + '\'' +
                '}';
    }
}

application.properties

#配置端口号
server.port=8082
#context-path
server.servlet.context-path=/myboot

#自定义key=value
school.name=动力节点
school.website=www.bjpowernode.com
school.address=北京的大兴区

site=www.bjpowernode.com

2.7 using jsp

SpringBoot does not recommend the use of jsp, but uses template technology instead of jsp

Using jsp requires configuration:

1) Add a dependency to process jsp. Responsible for compiling jsp files

<dependency>
    <groupId>org.apache.tomcat.embed</groupId>
    <artifactId>tomcat-embed-jasper</artifactId>
</dependency>
  1. If you need to use the functions of servlet, jsp, jstl
<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>jstl</artifactId>
</dependency>

<dependency>
	<groupId>javax.servlet</groupId>
	<artifactId>javax.servlet-api</artifactId>
</dependency>

<dependency>
<groupId>javax.servlet.jsp</groupId>
	<artifactId>javax.servlet.jsp-api</artifactId>
	<version>2.3.1</version>
</dependency>

  1. Create a directory to store jsp, generally called webapp

​ index.jsp

  1. It is necessary to specify the storage directory of the compiled jsp file in pom.xml.

META-INF/resources

5) Create Controller, access jsp

6) Configure the view resolver in the application.propertis file

2.8 Using containers

You want to get objects from the container through code.

Get the container through SpringApplication.run(Application.class, args); return value.


public static ConfigurableApplicationContext run(Class<?> primarySource, String... args) {
    
    
        return run(new Class[]{
    
    primarySource}, args);
}

ConfigurableApplicationContext : 接口,是ApplicationContext的子接口
public interface ConfigurableApplicationContext extends ApplicationContext

2.9 ComnandLineRunner interface, ApplcationRunner interface

Both interfaces have a run method. Execution time After the container object is created, the run() method is automatically executed.

You can complete some custom operations created in the container object.

@FunctionalInterface
public interface CommandLineRunner {
    
    
    void run(String... args) throws Exception;
}

@FunctionalInterface
public interface ApplicationRunner {
    
    
    void run(ApplicationArguments args) throws Exception;
}

Chapter 3 Web Components

Talk about three things: Interceptor, Servlet, Filter

3.1 Interceptors

An interceptor is an object in SpringMVC that can intercept requests to the Controller.

There are system interceptors in the interceptor framework, and interceptors can also be customized. Implement pre-processing of requests.

Implement a custom interceptor:

  1. Create a class that implements the HandlerInterceptor interface of the SpringMVC framework

    public interface HandlerInterceptor {
          
          
     default boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
          
          
         return true;
     }
    
     default void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable ModelAndView modelAndView) throws Exception {
          
          
     }
    
     default void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) throws Exception {
          
          
     }
    }
    

2. The interceptor needs to be declared in the configuration file of SpringMVC

<mvc:interceptors>
	<mvc:interceptor>
    	<mvc:path="url" />
        <bean class="拦截器类全限定名称"/>
    </mvc:interceptor>
</mvc:interceptors>

Register interceptors in SpringBoot:


@Configuration
public class MyAppConfig implements WebMvcConfigurer {
    
    

    //添加拦截器对象, 注入到容器中
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    
    

        //创建拦截器对象
        HandlerInterceptor interceptor = new LoginInterceptor();

        //指定拦截的请求uri地址
        String path []= {
    
    "/user/**"};
        //指定不拦截的地址
        String excludePath  [] = {
    
    "/user/login"};
        registry.addInterceptor(interceptor)
                .addPathPatterns(path)
                .excludePathPatterns(excludePath);

    }
}

3.2 Servlet

Use the Servlet object in the SpringBoot framework.

Steps for usage:

  1. Create a Servlet class. Create a class that inherits HttpServlet
  2. Register the Servlet so that the framework can find the Servlet

example:

1. Create a custom Servlet

//创建Servlet类
public class MyServlet extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        doPost(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
       //使用HttpServletResponse输出数据,应答结果
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out  = resp.getWriter();
        out.println("===执行的是Servlet==");
        out.flush();
        out.close();

    }
}
  1. Register Servlet
@Configuration
public class WebApplictionConfig {
    
    

    //定义方法, 注册Servlet对象
    @Bean
    public ServletRegistrationBean servletRegistrationBean(){
    
    

        //public ServletRegistrationBean(T servlet, String... urlMappings)
        //第一个参数是 Servlet对象, 第二个是url地址

        //ServletRegistrationBean bean =
                //new ServletRegistrationBean( new MyServlet(),"/myservlet");


        ServletRegistrationBean bean = new ServletRegistrationBean();
        bean.setServlet( new MyServlet());
        bean.addUrlMappings("/login","/test"); // <url-pattern>


        return bean;
    }
}

3.3 Filter Filter

Filter is a filter in the Servlet specification, which can process the request and adjust the parameters and attributes of the request. Often character encodings are handled in filters

Use filters in frames:

  1. Create a custom filter class
  2. Register Filter object

example:

// 自定义过滤器
public class MyFilter implements Filter {
    
    
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
    
    
        System.out.println("执行了MyFilter,doFilter ");
        filterChain.doFilter(servletRequest,servletResponse);
    }
}

Register Filter

@Configuration
public class WebApplicationConfig {
    
    

    @Bean
    public FilterRegistrationBean filterRegistrationBean(){
    
    
        FilterRegistrationBean bean  = new FilterRegistrationBean();
        bean.setFilter( new MyFilter());
        bean.addUrlPatterns("/user/*");
        return bean;
    }
}

3.4 Character set filter

CharacterEncodingFilter : Solve the problem of garbled characters in post requests

In the SpringMVC framework, register filters in web.xml. Configure its properties.

The first way:

Steps for usage:

  1. Configure character set filter

    @Configuration
    public class WebSystemConfig {
          
          
    
        //注册Servlet
        @Bean
        public ServletRegistrationBean servletRegistrationBean(){
          
          
            MyServlet myServlet = new MyServlet();
            ServletRegistrationBean reg = new ServletRegistrationBean(myServlet,"/myservlet");
            return reg;
        }
    
    
        //注册Filter
        @Bean
        public FilterRegistrationBean filterRegistrationBean(){
          
          
            FilterRegistrationBean reg = new FilterRegistrationBean();
    
            //使用框架中的过滤器类
            CharacterEncodingFilter filter  = new CharacterEncodingFilter();
            //指定使用的编码方式
            filter.setEncoding("utf-8");
            //指定request , response都使用encoding的值
            filter.setForceEncoding(true);
    
            reg.setFilter(filter);
            //指定 过滤的url地址
            reg.addUrlPatterns("/*");
    
    
            return reg;
        }
    }
    
  2. Modify the application.properties file to allow custom filters to work

#SpringBoot中默认已经配置了CharacterEncodingFilter。 编码默认ISO-8859-1
#设置enabled=false 作用是关闭系统中配置好的过滤器, 使用自定义的CharacterEncodingFilter
server.servlet.encoding.enabled=false

the second way

Modify the application.properties file

server.port=9001
server.servlet.context-path=/myboot

#让系统的CharacterEncdoingFilter生效
server.servlet.encoding.enabled=true
#指定使用的编码方式
server.servlet.encoding.charset=utf-8
#强制request,response都使用charset属性的值
server.servlet.encoding.force=true

Chapter 4 ORM Operation MySQL

Use the MyBatis framework to manipulate data and integrate MyBatis with the SpringBoot framework

Steps for usage:

  1. Mybatis start-up dependency: complete the automatic configuration of mybatis objects, and put the objects in the container

  2. pom.xml specifies to include the xml file in the src/main/java directory into the classpath

  3. Create entity class Student

  4. Create a Dao interface StudentDao and create a method to query students

  5. Create the Mapper file corresponding to the Dao interface, the xml file, and write the sql statement

  6. Create a Service layer object, create a StudentService interface and its implementation class. The method to go to the dao object. Complete the database operation

  7. Create a Controller object and access the Service.

  8. Write application.properties file

    Configure the connection information for the database.

The first way: @Mapper

@Mapper: Placed on top of the dao interface, each interface needs to use this annotation.

/**
 * @Mapper:告诉MyBatis这是dao接口,创建此接口的代理对象。
 *     位置:在类的上面
 */
@Mapper
public interface StudentDao {
    
    

    Student selectById(@Param("stuId") Integer id);
}

The second way @MapperScan

/**
 * @MapperScan: 找到Dao接口和Mapper文件
 *     basePackages:Dao接口所在的包名
 */
@SpringBootApplication
@MapperScan(basePackages = {
    
    "com.bjpowernode.dao","com.bjpowernode.mapper"})
public class Application {
    
    
}

The third way: Mapper files and Dao interfaces are managed separately

Now put the Mapper file in the resources directory

1) Create a subdirectory (custom) in the resources directory, such as mapper

2) Put the mapper file in the mapper directory

3) In the application.properties file, specify the directory of the mapper file

#指定mapper文件的位置
mybatis.mapper-locations=classpath:mapper/*.xml
#指定mybatis的日志
mybatis.configuration.log-impl=org.apache.ibatis.logging.stdout.StdOutImpl
  1. Specify in pom.xml to compile the files in the resources directory into the target directory
<!--resources插件-->
<resources>
   <resource>
      <directory>src/main/resources</directory>
      <includes>
         <include>**/*.*</include>
      </includes>
   </resource>
</resources>

fourth business

Transactions in the Spring framework:

1) Objects that manage transactions: transaction managers (interfaces, interfaces have many implementation classes)

​ For example: use Jdbc or mybatis to access the database, the transaction manager used: DataSourceTransactionManager

2) Declarative transaction: In the xml configuration file or use annotations to describe the content of transaction control

​ Control transactions: isolation level, propagation behavior, timeout

3) Transaction processing method:

1) @Transactional in the Spring Framework

2) The aspectj framework can declare the content of transaction control in the xml configuration file

Using transactions in SpringBoot: Both of the above methods are fine.

1) Add @Transactional above the business method. After adding the annotation, the method has a transaction function.

2) Clearly above the main startup class, add @EnableTransactionManager

example:

/**
 * @Transactional: 表示方法的有事务支持
 *       默认:使用库的隔离级别, REQUIRED 传播行为; 超时时间  -1
 *       抛出运行时异常,回滚事务
 */
@Transactional
@Override
public int addStudent(Student student) {
    
    
    System.out.println("业务方法addStudent");
    int rows  =  studentDao.insert(student);
    System.out.println("执行sql语句");

    //抛出一个运行时异常, 目的是回滚事务
    //int m   = 10 / 0 ;

    return rows;
}

Chapter 5 Interface Architecture Style—RESTful

Interface: API (Application Programming Interface, application programming interface) is some predefined interfaces (such as functions, HTTP interfaces), or refers to the agreement of different components of the software system . A set of routines that applications and developers can access based on a piece of software or hardware without accessing the source code or understanding the details of the inner workings .

Interface (API): It can refer to accessing servlets, urls of controllers, and calling functions of other programs

Architecture style: api organization method (look)

Just a traditional one: http://localhost:9002/mytrans/addStudent?name=lisi&age=26

​ Provide the access resource name addStudent on the address, and then use the get method to pass parameters.

5.1 REST

RESTful architectural style

1) REST: (English: Representational State Transfer, Chinese: presentation layer state transfer).

REST: It is an interface architectural style and design concept, not a standard.

Advantages: more concise and more layered

Presentation layer state transition:

​ The presentation layer is the view layer, which displays resources, and displays the results of operating resources through view pages, jsp, etc.

​ Status: Resource Change

​ Transfer: Resources can change. Resources can be created, new status, resources can be queried after resources are created, and the content of resources can be seen,

The content of this resource can be modified, and the resource after modification is different from the previous one.

2) Elements in REST:

Use REST to represent resources and operations on resources. In the Internet, represents a resource or an operation.

Resources are represented by urls. On the Internet, pictures, videos, texts, web pages, etc. used are all resources.

Resources are represented by nouns.

For resources:

​ Query resources: Look, find resources through url.

​ Create resource: add resource

​ Update resources: update resources, edit

​ Delete resources: remove

Resources are represented by urls, and resources are represented by nouns.

​ In url, use nouns to represent resources and access resource information, and in url, use "/" to separate resource information

​ http://localhost:8080/myboot/student/1001

Use the action (request method) in http to represent the operation on resources (CURD)

GET: query resource – sql select

​ Dealing with a single resource: use its singular form

​ http://localhost:8080/myboot/student/1001

​ http://localhost:8080/myboot/student/1001/1

​ Handling Multiple Resources: Use Plurals

​ http://localhost:8080/myboot/students/1001/1002

POST: create resource – sql insert

​ http://localhost:8080/myboot/student

​ Pass data in post request

<form action="http://localhost:8080/myboot/student" method="post">
	姓名:<input type="text" name="name" />
    年龄:<input type="text" name="age" />
  </form>

PUT: update resource – sql update

<form action="http://localhost:8080/myboot/student/1" method="post">
 姓名:<input type="text" name="name" />
 年龄:<input type="text" name="age" />
      <input type="hidden" name="_method" value="PUT" />
</form>

DELETE: delete resource – sql delete

```xml

Delete the data of
1```

The required paging, sorting and other parameters are still placed after the url, for example

http://localhost:8080/myboot/students?page=1&pageSize=20

`

3) Explain REST in one sentence:

​ Use url to represent resources, and use http actions to operate resources.

  1. annotation

@PathVariable : get data from url

@GetMapping: Supported get request methods, equivalent to @RequestMapping( method=RequestMethod.GET)

@PostMapping: Support post request method, equivalent to @RequestMapping( method=RequestMethod.POST)

@PutMapping: Support put request method, equivalent to @RequestMapping( method=RequestMethod.PUT)

@DeleteMapping: Support delete request method, equivalent to @RequestMapping( method=RequestMethod.DELETE)

@RestController: Conforms to the annotation and is a combination of @Controller and @ResponseBody.

​ Using @RestController above the class means that all methods of the current class have been added to @ResponseBody

  1. Postman : testing tool

    Use Postman: you can test get, post, put, delete and other requests

5.2 Support put and delete requests in the page or ajax

There is a filter in SpringMVC that supports post requests to put and delete

Filter: org.springframework.web.filter.HiddenHttpMethodFilter

Function: Convert the post request in the request to put, delete

Implementation steps:

  1. application.properties(yml) : enable HiddenHttpMethodFilter filter
  2. In the request page, include the _method parameter, its value is put, delete, the post method used to initiate this request

Chapter 6 Redis

Redis: A NoSQL database, often used as a cache (cache)

Redis data types: string, hash, set, zset, list

Redis is a middleware: is an independent server.

Famous clients in java: Jedis, lettuce, Redisson

There is a RedisTemplate (StringRedisTemplate) in Spring, SpringBoot, which handles interaction with redis

6.1 Configure the Windows version of redis

Decompress Redis-x64-3.2.100.rar to a non-Chinese directory

redis-server.exe: server, after starting, do not close

redis-cli.exe: client, access data in redis

redisclient-win32.x86_64.2.0.jar : Redis GUI client

Execution method: In the directory where this file is located, execute java -jar redisclient-win32.x86_64.2.0.jar

lettuce client library used by RedisTemplate

<!--redis起步依赖: 直接在项目中使用RedisTemplate(StringRedisTemplate)-->
<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
data-redis使用的   lettuce 客户端库

在程序中使用RedisTemplate类的方法 操作redis数据, 实际就是调用的lettuce 客户端的中的方法


6.2 Comparing StringRedisTemplate and RedisTemplate

StringRedisTemplate: Treat k and v as String, using String serialization, good readability

RedisTemplate: Store k and v in redis after serialization. k, v are the serialized content and cannot be identified directly.

​ The jdk serialization used by default can be modified as the premise serialization

Serialization: The process of converting an object into a transferable sequence of bytes is called serialization.

Deserialization: The process of restoring a sequence of bytes to an object is called deserialization.

Why serialization is needed

The ultimate goal of serialization is to allow objects to be stored across platforms and transmitted over the network. And our way of cross-platform storage and network transmission is IO, and the data format supported by our IO is byte array. We must formulate a rule (serialization) when converting the object into a byte array, then when we read the data from the IO stream, we will restore the object back (deserialization) according to this rule.

When do you need to serialize

Through the above, I think you already know that all data that needs to be "cross-platform storage" and "network transmission" needs to be serialized.

In essence, both storage and network transmission need to save an object state into a cross-platform recognized byte format, and then other platforms can parse and restore object information through byte information.

way of serialization

Serialization is just a rule for disassembling and assembling objects, so there must be a variety of such rules. For example, the common serialization methods are:

JDK (does not support cross-language), JSON, XML, Hessian, Kryo (does not support cross-language), Thrift, Protofbuff,

Student( name=zs, age=20) ---- { “name”:“zs”, “age”:20 }

Java serialization: convert java objects to byte[], binary data

json serialization: The json serialization function converts objects to and from JSON format. For example, convert a Student object into a JSON string {"name":"Li Si", "age":29}), deserialize (convert the JSON string {"name":"Li Si", "age": 29} converted to Student object)

Set the serialization method of key or value

// 使用RedisTemplate ,在存取值之前,设置序列化
// 设置 key 使用String的序列化
redisTemplate.setKeySerializer( new StringRedisSerializer());

// 设置 value 的序列化
redisTemplate.setValueSerializer( new StringRedisSerializer());

redisTemplate.opsForValue().set(k,v);

Chapter 7 SpringBoot Integrate Dubbo

7.1 Look at the SpringBoot inheritance Dubbo document

https://github.com/apache/dubbo-spring-boot-project/blob/master/README_CN.md

7.2 Public projects

Independent maven project: defines the interface and data class

public class Student implements Serializable {
    
    
    private static final long serialVersionUID = 1901229007746699151L;

    private Integer id;
    private String name;
    private Integer age;
}

public interface StudentService {
    
    

    Student queryStudent(Integer id);
}

7.3 Provider

Create a SpringBoot project

1) pom.xml

<dependencies>

   <!--加入公共项目的gav-->
   <dependency>
      <groupId>com.bjpowernode</groupId>
      <artifactId>022-interface-api</artifactId>
      <version>1.0.0</version>
   </dependency>

   <!--dubbo依赖-->
   <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-spring-boot-starter</artifactId>
      <version>2.7.8</version>
   </dependency>


   <!--zookeeper依赖-->
   <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-dependencies-zookeeper</artifactId>
      <version>2.7.8</version>
      <type>pom</type>
      <exclusions>
         <!-- 排除log4j依赖 -->
         <exclusion>
            <artifactId>slf4j-log4j12</artifactId>
            <groupId>org.slf4j</groupId>
         </exclusion>
      </exclusions>
   </dependency>
</dependencies>

2) Implement the interface

/**
 * 使用dubbo中的注解暴露服务
 * @Component 可以不用加
 */
@DubboService(interfaceClass = StudentService.class,version = "1.0",timeout = 5000)
public class StudentServiceImpl implements StudentService {
    
    
    @Override
    public Student queryStudent(Integer id) {
    
    
        Student student  = new Student();
        if( 1001 == id){
    
    
            student.setId(1001);
            student.setName("------1001-张三");
            student.setAge(20);
        } else if(1002  == id){
    
    
            student.setId(1002);
            student.setName("#######1002-李四");
            student.setAge(22);
        }

        return student;
    }
}

3)application.properties

#配置服务名称 dubbo:application name="名称"
spring.application.name=studentservice-provider

#配置扫描的包, 扫描的@DubboService
dubbo.scan.base-packages=com.bjpowernode.service

#配置dubbo协议
#dubbo.protocol.name=dubbo
#dubbo.protocol.port=20881

#注册中心
dubbo.registry.address=zookeeper://localhost:2181

4) Above the startup class

@SpringBootApplication
@EnableDubbo
public class ProviderApplication {
    
    

   public static void main(String[] args) {
    
    
      SpringApplication.run(ProviderApplication.class, args);
   }
}

7.4 Consumers

Create a SpringBoot project

1) pom.xml

<dependencies>

   <!--加入公共项目的gav-->
   <dependency>
      <groupId>com.bjpowernode</groupId>
      <artifactId>022-interface-api</artifactId>
      <version>1.0.0</version>
   </dependency>

   <!--dubbo依赖-->
   <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-spring-boot-starter</artifactId>
      <version>2.7.8</version>
   </dependency>


   <!--zookeeper依赖-->
   <dependency>
      <groupId>org.apache.dubbo</groupId>
      <artifactId>dubbo-dependencies-zookeeper</artifactId>
      <version>2.7.8</version>
      <type>pom</type>
      <exclusions>
         <!-- 排除log4j依赖 -->
         <exclusion>
            <artifactId>slf4j-log4j12</artifactId>
            <groupId>org.slf4j</groupId>
         </exclusion>
      </exclusions>
   </dependency>
</dependencies>
  1. You can create a Controller or a Service
@RestController
public class DubboController {
    
    

    /**
     * 引用远程服务, 把创建好的代理对象,注入给studentService
     */
    //@DubboReference(interfaceClass = StudentService.class,version = "1.0")

    /**
     * 没有使用interfaceClass,默认的就是 引用类型的 数据类型
      */
    @DubboReference(version = "1.0")
    private StudentService studentService;

    @GetMapping("/query")
    public String queryStudent(Integer id){
    
    
        Student student   = studentService.queryStudent(id);
        return "调用远程接口,获取对象:"+student;
    }
}

3)application.properties

#指定服务名称
spring.application.name=consumer-application
#指定注册中心
dubbo.registry.address=zookeeper://localhost:2181

7.5 Exercises

Technologies used: SpringBoot, Dubbo, Redis, MyBatis

Student table:

[External link picture transfer failed, the source site may have an anti-theft link mechanism, it is recommended to save the picture and upload it directly (img-wSlqMpba-1683208502333) (D:\course\25-SpringBoot\notes\images\image-20210119150418295.png) ]

CREATE TABLE student (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(255) COLLATE utf8_bin DEFAULT NULL,
phone varchar(11) COLLATE utf8_bin DEFAULT NULL,
age int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8 COLLATE=utf8_bin;

  1. registered student

​ The phone must be unique. If the phone number already exists, the registration will fail.

​ int addStudent(Student student);

​ Return value: int

​ 1: Registered successfully

​ 2: The phone number already exists

​ name must be at least two characters,

​ age must be greater than 0

2) Query students, according to the id query, this student.

​ First go to redis to query the students, if there is no such student in redis, query from the database, and put the queried students into redis.

​ You can query this student again later and it should be available from redis.

​ Student queryStudent(Integer id);

  1. Using the Dubbo framework, addStudent and queryStudent are implemented by service providers.

​ The consumer can be a Controller that calls the two methods of the provider. Realize registration and query.

4) The page uses html and ajax, jquery.

​ Provide a form to register students on the html page, and provide a text box to enter the id for query.

Both registration and query use ajax technology.

​ html, jquery.js are placed in the resources/static directory

Chapter 8 Packing

8.1 Packaging war

1. Created a jsp application

2. Modify pom.xml

1) Specify the packaged file name

<build>
   <!--打包后的文件名称-->
   <finalName>myboot</finalName>
</build>

2) Specify the jsp compilation directory

<!--resources插件, 把jsp编译到指定的目录-->
<resources>
   <resource>
      <directory>src/main/webapp</directory>
      <targetPath>META-INF/resources</targetPath>
      <includes>
         <include>**/*.*</include>
      </includes>
   </resource>

   <!--使用了mybatis ,而且mapper文件放在src/main/java目录-->
   <resource>
      <directory>src/main/java</directory>
      <includes>
         <include>**/*.xml</include>
      </includes>
   </resource>

   <!--把src/main/resources下面的所有文件,都包含到classes目录-->
   <resource>
      <directory>src/main/resources</directory>
      <includes>
         <include>**/*.*</include>
      </includes>
   </resource>
</resources>

3) The execution package is war

<!--打包类型-->
<packaging>war</packaging>

4) The main startup class inherits SpringBootServletInitializer

/**
 * SpringBootServletInitializer: 继承这个类, 才能使用独立tomcat服务器
 */
@SpringBootApplication
public class JspApplication  extends SpringBootServletInitializer  {
    
    

   public static void main(String[] args) {
    
    
      SpringApplication.run(JspApplication.class, args);
   }

   @Override
   protected SpringApplicationBuilder configure(SpringApplicationBuilder builder) {
    
    
      return builder.sources(JspApplication.class);
   }
}

5) Deploy war

Put the war in the release directory of the server such as tomcat. Take tomcat as an example, put myboot.war in the tomcat/webapps directory.

8.2 Packaging as jar

1. Created a project that contains jsp

2. Modify pom.xml

​ 1) Specify the packaged file name

<build>
   <!--打包后的文件名称-->
   <finalName>myboot</finalName>
</build>
  1. Specify the springboot-maven-plugin version
<plugins>
   <plugin>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-maven-plugin</artifactId>
      <!--打包jar, 有jsp文件时,必须指定maven-plugin插件的版本是 1.4.2.RELEASE-->
      <version>1.4.2.RELEASE</version>
   </plugin>
</plugins>

3) Finally execute maven clean package

​ In the target directory, generate a jar file, the example is myboot.jar

​ Execute an independent springboot project in cmd java -jar myboot.jar

Chapter 9 Thymeleaf Template Engine

Thymeleaf: It is a template technology developed in java and runs on the server side. Send the processed data to the browser.

​ Templates work as view layers. display data. Thymeleaf is based on the Html language. Thymleaf syntax is applied in

​ in the html tag. The SpringBoot framework integrates Thymeleaf, using Thymeleaf instead of jsp.

Thymeleaf's official website: http://www.thymeleaf.org
Thymeleaf official manual: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html

9.1 Expressions

  1. standard variable expression

    Syntax: ${key}

    Function: Get the text data of the key pair, key is the key in the request scope, use request.setAttribute(), model.addAttribute()

    In the html tag in the page, use th:text="${key}"

<div style="margin-left: 400px">
    <h3>标准变量表达式:  ${key}</h3>
    <p th:text="${site}">key不存在</p>
    <br/>
    <p>获取SysUser对象 属性值</p>
    <p th:text="${myuser.id}">id</p>
    <p th:text="${myuser.name}">姓名</p>
    <p th:text="${myuser.sex}">姓名:m男</p>
    <p th:text="${myuser.age}">年龄</p>
    <p th:text="${myuser.getName()}">获取姓名使用getXXX</p>
</div>
  1. Select variable expression (asterisk variable expression)

    Syntax: *{key}

    Function: To get the data corresponding to this key, *{key} needs to be used together with the attribute th:object.

    The purpose is to simply get the property value of an object.

    <p>使用 *{} 获取SysUser的属性值</p>
    <div th:object="${myuser}">
        <p th:text="*{id}"></p>
        <p th:text="*{name}"></p>
        <p th:text="*{sex}"></p>
        <p th:text="*{age}"></p>
    
    </div>
    <p>使用*{}完成的表示 对象的属性值</p>
    <p th:text="*{myuser.name}" ></p>
    
  2. link expression

    Syntax: @{url}

    Role: Indicates the link, can

     <script src="..."> , <link href="..."> <a href=".."> ,<form action="..."> <img src="...">
    

9.2 Thymeleaf Properties

The attribute is placed in the html element, which is the attribute of the html element, and the th prefix is ​​added. The effect of the attribute is unchanged. Adding th, the value of the attribute is handled by the template engine. Variable expressions can be used in attributes

For example:

<form action="/loginServlet" method="post"></form>

<form th:action="/loginServlet" th:method="${methodAttr}"></form>

9.3 each

each loop, you can loop List, Array

grammar:

In an html tag, use th:each

<div th:each="集合循环成员,循环的状态变量:${key}">
    <p th:text="${集合循环成员}" ></p>
</div>

集合循环成员,循环的状态变量:两个名称都是自定义的。 “循环的状态变量”这个名称可以不定义,默认是"集合循环成员Stat"


each loopMap

In an html tag, use th:each

<div th:each="集合循环成员,循环的状态变量:${key}">
    <p th:text="${集合循环成员.key}" ></p>
    <p th:text="${集合循环成员.value}" ></p>
</div>

集合循环成员,循环的状态变量:两个名称都是自定义的。 “循环的状态变量”这个名称可以不定义,默认是"集合循环成员Stat"

key:map集合中的key
value:map集合key对应的value值

9.4 th:if

"th:if": Judgment statement, when the condition is true, display the body of the html tag, otherwise it does not display no else statement

语法:
<div th:if=" 10 > 0 "> 显示文本内容 </div>

There is also a th:unless and th:if opposite behavior

语法:
<div th:unless=" 10 < 0 "> 当条件为false显示标签体内容 </div>

Example: if

<div style="margin-left: 400px">
        <h3> if 使用</h3>
        <p th:if="${sex=='m'}">性别是男</p>
        <p th:if="${isLogin}">已经登录系统</p>
        <p th:if="${age > 20}">年龄大于20</p>
        <!--""空字符是true-->
        <p th:if="${name}">name是“”</p>
        <!--null是false-->
        <p th:if="${isOld}"> isOld是null</p>
 </div>

Example: unless

 <div style="margin-left: 400px">
        <h3>unless: 判断条件为false,显示标签体内容</h3>
        <p th:unless="${sex=='f'}">性别是男的</p>
        <p th:unless="${isLogin}">登录系统</p>
        <p th:unless="${isOld}"> isOld是null </p>
 </div>

9.5 th:switch

th: switch is the same as switch in java

语法:
<div th:switch="要比对的值">
    <p th:case="值1">
        结果1
    </p>
    <p th:case="值2">
        结果2
    </p>
    <p th:case="*">
        默认结果
    </p>
    以上的case只有一个语句执行
    
</div>

9.6 th:inline

  1. Inline text: outside the html tag, get the value of the expression

    grammar:

    <p>显示姓名是:[[${key}]]</p>
    
     <div style="margin-left: 400px">
            <h3>内联 text, 使用内联表达式显示变量的值</h3>
            <div th:inline="text">
                <p>我是[[${name}]],年龄是[[${age}]]</p>
                我是<span th:text="${name}"></span>,年龄是<span th:text="${age}"></span>
            </div>
    
            <div>
                <p>使用内联text</p>
                <p>我是[[${name}]],性别是[[${sex}]]</p>
            </div>
    </div>
    
  2. inline javascript

例子:
 <script type="text/javascript" th:inline="javascript">
         var myname = [[${
      
      name}]];
         var myage = [[${
      
      age}]];

         //alert("获取的模板中数据 "+ myname + ","+myage)

        function fun(){
      
      
            alert("单击事件,获取数据 "+ myname + ","+ [[${
      
      sex}]])
        }
    </script>

9.7 Literals

example:

 <div style="margin-left: 400px">
       <h3>文本字面量: 使用单引号括起来的字符串</h3>
       <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>

       <h3>数字字面量</h3>
        <p th:if="${20>5}"> 20大于 5</p>

        <h3>boolean字面量</h3>
        <p th:if="${isLogin == true}">用户已经登录系统</p>

        <h3>null字面量</h3>
        <p th:if="${myuser != null}">有myuser数据</p>
    </div>

9.8 String concatenation

The connection string has two syntaxes

1) The syntax uses single quotes to enclose strings, and + to connect other strings or expressions

  <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>

2) Syntax: use double vertical bars, |strings and expressions|

<p th:text="|我是${name},我所在城市${city|">
    显示数据
</p>

example:

    <div style="margin-left: 400px">
       <h3>字符串连接方式1:使用单引号括起来的字符串</h3>
       <p th:text="'我是'+${name}+',我所在的城市'+${city}">数据显示</p>
        <br/>
        <br/>
        <h3>字符串连接方式2:|字符串和表达式|</h3>
        <p th:text="|我是${name},所在城市${city},其他人${myuser.name}|"></p>
    </div>

9.9 Operators

算术运 算: + , - - , * , / , %
关系比较 : > , < , >= , <= ( gt , lt , ge , le )
相等判断: == , != ( eq , ne )


<div style="margin-left: 400px">
        <h3>使用运算符</h3>
        <p th:text="${age > 10}">年龄大于 10 </p>
        <p th:text="${ 20 + 30 }">显示运算结果</p>
        <p th:if="${myuser == null}">myuser是null</p>
        <p th:if="${myuser eq null}">myuser是null</p>
        <p th:if="${myuser ne null}">myuser不是null</p>

        <p th:text="${isLogin == true ? '用户已经登录' : '用户需要登录'}"></p>
        <p th:text="${isLogin == true ? ( age > 10 ? '用户是大于10的' : '用户年龄比较小') : '用户需要登录'}"></p>

    </div>

三元运算符:
 表达式  ? true的结果 : false的结果

三元运算符可以嵌套

9.10 Built-in objects

Document address: https://www.thymeleaf.org/doc/tutorials/3.0/usingthymeleaf.html#web-context-namespaces-for-requestsession-attributes-etc.

#request means HttpServletRequest

#session represents the HttpSession object

session represents the Map object, which is a simple representation of #session, used to obtain the value of the key specified in the session

​ #session.getAttribute(“loginname”) == session.loginname

These are built-in objects and can be used directly in template files.

例子:
 <div style="margin-left: 350px">
        <h3>内置对象#request,#session,session的使用</h3>
        <p>获取作用域中的数据</p>
        <p th:text="${#request.getAttribute('requestData')}"></p>
        <p th:text="${#session.getAttribute('sessionData')}"></p>
        <p th:text="${session.loginname}"></p>

        <br/>
        <br/>
        <h3>使用内置对象的方法</h3>
        getRequestURL=<span th:text="${#request.getRequestURL()}"></span><br/>
        getRequestURI=<span th:text="${#request.getRequestURI()}"></span><br/>
        getQueryString=<span th:text="${#request.getQueryString()}"></span><br/>
        getContextPath=<span th:text="${#request.getContextPath()}"></span><br/>
        getServerName=<span th:text="${#request.getServerName()}"></span><br/>
        getServerPort=<span th:text="${#request.getServerPort()}"></span><br/>
</div>

9.11 Built-in utility classes

Built-in tool types: some of Thymeleaf's own classes, providing some processing methods for string, date, and collections

#dates: A utility class for dealing with dates

#numbers: Handling numbers

#lists: processing list collection

<div style="margin-left: 350px">
      <h3>日期类对象 #dates</h3>
      <p th:text="${#dates.format(mydate )}"></p>
      <p th:text="${#dates.format(mydate,'yyyy-MM-dd')}"></p>
      <p th:text="${#dates.format(mydate,'yyyy-MM-dd HH:mm:ss')}"></p>
      <p th:text="${#dates.year(mydate)}"></p>
      <p th:text="${#dates.month(mydate)}"></p>
      <p th:text="${#dates.monthName(mydate)}"></p>
      <p th:text="${#dates.createNow()}"></p>
      <br/>

      <h3>内置工具类#numbers,操作数字的</h3>
      <p th:text="${#numbers.formatCurrency(mynum)}"></p>
      <p th:text="${#numbers.formatDecimal(mynum,5,2)}"></p>

      <br/>
      <h3>内置工具类#strings,操作字符串</h3>
      <p th:text="${#strings.toUpperCase(mystr)}"></p>
      <p th:text="${#strings.indexOf(mystr,'power')}"></p>
      <p th:text="${#strings.substring(mystr,2,5)}"></p>
      <p th:text="${#strings.substring(mystr,2)}"></p>
      <p th:text="${#strings.concat(mystr,'---java开发的黄埔军校---')}"></p>
      <p th:text="${#strings.length(mystr)}"></p>
      <p th:text="${#strings.length('hello')}"></p>
      <p th:unless="${#strings.isEmpty(mystr)}"> mystring 不是 空字符串  </p>

      <br/>
      <h3>内置工具类#lists,操作list集合</h3>
      <p th:text="${#lists.size(mylist)}"></p>
      <p th:if="${#lists.contains(mylist,'a')}">有成员a</p>
      <p th:if="!${#lists.isEmpty(mylist)}"> list 集合有多个成员</p>

      <br/>
      <h3>处理null</h3>
      <p th:text="${zoo?.dog?.name}"></p>

  </div>

9.12 Custom Template

Templates are content reuse, defined once, and used multiple times in other template files.

Template usage:

1. Define the template

2. Using Templates

Template definition syntax:

th:fragment="模板自定义名称"

例如:
<div th:fragment="head">
    <p>
        动力节点-java开发
    </p>
    <p>
        www.bjpowernode.com
    </p>
</div>

Quote template syntax:

1) ~{templatename :: selector}
   templatename:  文件名称
   selector: 自定义模板名称
2)templatename :: selector
   templatename:  文件名称
   selector: 自定义模板名称

对于使用模板:有包含模板(th:include), 插入模板(th:insert)

Chapter 10 Summary

10.1 Notes

Spring + SpringMVC + SpringBoot

创建对象的:
@Controller: 放在类的上面,创建控制器对象,注入到容器中
@RestController: 放在类的上面,创建控制器对象,注入到容器中。
             作用:复合注解是@Controller , @ResponseBody, 使用这个注解类的,里面的控制器方法的返回值                   都是数据

@Service : 放在业务层的实现类上面,创建service对象,注入到容器
@Repository : 放在dao层的实现类上面,创建dao对象,放入到容器。 没有使用这个注解,是因为现在使用MyBatis框               架,  dao对象是MyBatis通过代理生成的。 不需要使用@Repository、 所以没有使用。
@Component:  放在类的上面,创建此类的对象,放入到容器中。 

赋值的:
@Value : 简单类型的赋值, 例如 在属性的上面使用@Value("李四") private String name
          还可以使用@Value,获取配置文件者的数据(properties或yml)。 
          @Value("${server.port}") private Integer port

@Autowired: 引用类型赋值自动注入的,支持byName, byType. 默认是byType 。 放在属性的上面,也可以放在构造             方法的上面。 推荐是放在构造方法的上面
@Qualifer:  给引用类型赋值,使用byName方式。   
            @Autowird, @Qualifer都是Spring框架提供的。

@Resource : 来自jdk中的定义, javax.annotation。 实现引用类型的自动注入, 支持byName, byType.
             默认是byName, 如果byName失败, 再使用byType注入。 在属性上面使用


其他:
@Configuration : 放在类的上面,表示这是个配置类,相当于xml配置文件

@Bean:放在方法的上面, 把方法的返回值对象,注入到spring容器中。

@ImportResource : 加载其他的xml配置文件, 把文件中的对象注入到spring容器中

@PropertySource : 读取其他的properties属性配置文件

@ComponentScan: 扫描器 ,指定包名,扫描注解的

@ResponseBody: 放在方法的上面,表示方法的返回值是数据, 不是视图
@RequestBody : 把请求体中的数据,读取出来, 转为java对象使用。

@ControllerAdvice:  控制器增强, 放在类的上面, 表示此类提供了方法,可以对controller增强功能。

@ExceptionHandler : 处理异常的,放在方法的上面

@Transcational :  处理事务的, 放在service实现类的public方法上面, 表示此方法有事务


SpringBoot中使用的注解
    
@SpringBootApplication : 放在启动类上面, 包含了@SpringBootConfiguration
                          @EnableAutoConfiguration@ComponentScan


    
MyBatis相关的注解

@Mapper : 放在类的上面 , 让MyBatis找到接口, 创建他的代理对象    
@MapperScan :放在主类的上面 , 指定扫描的包, 把这个包中的所有接口都创建代理对象。 对象注入到容器中
@Param : 放在dao接口的方法的形参前面, 作为命名参数使用的。
    
Dubbo注解
@DubboService: 在提供者端使用的,暴露服务的, 放在接口的实现类上面
@DubboReference:  在消费者端使用的, 引用远程服务, 放在属性上面使用。
@EnableDubbo : 放在主类上面, 表示当前引用启用Dubbo功能。
    
    
    
    
    


    


With template syntax:

1) ~{templatename :: selector}
   templatename:  文件名称
   selector: 自定义模板名称
2)templatename :: selector
   templatename:  文件名称
   selector: 自定义模板名称

对于使用模板:有包含模板(th:include), 插入模板(th:insert)

Chapter 10 Summary

10.1 Notes

Spring + SpringMVC + SpringBoot

创建对象的:
@Controller: 放在类的上面,创建控制器对象,注入到容器中
@RestController: 放在类的上面,创建控制器对象,注入到容器中。
             作用:复合注解是@Controller , @ResponseBody, 使用这个注解类的,里面的控制器方法的返回值                   都是数据

@Service : 放在业务层的实现类上面,创建service对象,注入到容器
@Repository : 放在dao层的实现类上面,创建dao对象,放入到容器。 没有使用这个注解,是因为现在使用MyBatis框               架,  dao对象是MyBatis通过代理生成的。 不需要使用@Repository、 所以没有使用。
@Component:  放在类的上面,创建此类的对象,放入到容器中。 

赋值的:
@Value : 简单类型的赋值, 例如 在属性的上面使用@Value("李四") private String name
          还可以使用@Value,获取配置文件者的数据(properties或yml)。 
          @Value("${server.port}") private Integer port

@Autowired: 引用类型赋值自动注入的,支持byName, byType. 默认是byType 。 放在属性的上面,也可以放在构造             方法的上面。 推荐是放在构造方法的上面
@Qualifer:  给引用类型赋值,使用byName方式。   
            @Autowird, @Qualifer都是Spring框架提供的。

@Resource : 来自jdk中的定义, javax.annotation。 实现引用类型的自动注入, 支持byName, byType.
             默认是byName, 如果byName失败, 再使用byType注入。 在属性上面使用


其他:
@Configuration : 放在类的上面,表示这是个配置类,相当于xml配置文件

@Bean:放在方法的上面, 把方法的返回值对象,注入到spring容器中。

@ImportResource : 加载其他的xml配置文件, 把文件中的对象注入到spring容器中

@PropertySource : 读取其他的properties属性配置文件

@ComponentScan: 扫描器 ,指定包名,扫描注解的

@ResponseBody: 放在方法的上面,表示方法的返回值是数据, 不是视图
@RequestBody : 把请求体中的数据,读取出来, 转为java对象使用。

@ControllerAdvice:  控制器增强, 放在类的上面, 表示此类提供了方法,可以对controller增强功能。

@ExceptionHandler : 处理异常的,放在方法的上面

@Transcational :  处理事务的, 放在service实现类的public方法上面, 表示此方法有事务


SpringBoot中使用的注解
    
@SpringBootApplication : 放在启动类上面, 包含了@SpringBootConfiguration
                          @EnableAutoConfiguration@ComponentScan


    
MyBatis相关的注解

@Mapper : 放在类的上面 , 让MyBatis找到接口, 创建他的代理对象    
@MapperScan :放在主类的上面 , 指定扫描的包, 把这个包中的所有接口都创建代理对象。 对象注入到容器中
@Param : 放在dao接口的方法的形参前面, 作为命名参数使用的。
    
Dubbo注解
@DubboService: 在提供者端使用的,暴露服务的, 放在接口的实现类上面
@DubboReference:  在消费者端使用的, 引用远程服务, 放在属性上面使用。
@EnableDubbo : 放在主类上面, 表示当前引用启用Dubbo功能。
    
    
    
    
    


    


Guess you like

Origin blog.csdn.net/m0_47015897/article/details/130496194