Framework annotation summary (about SSM, SpringBoot, SpringCloud, etc.)

Preface

In the process of learning the framework, you will encounter a lot of annotations, it is very easy to forget and confuse! This blog is a summary of the various framework annotations I encountered during my study . The technical blog will continue to be updated as we study . The blog is not over yet, it is recommended to collect it.

One, MyBatis annotation

1、@Alias

Function: Set an alias for the Java class to facilitate the call of the attributes (parameterType, resultType) in the Mapper.xml mapping file. In the following code, user is the alias of the class .

@Alias("user") 
public class User {
    
    
	
}

2、@select、@update、@delete、@insert

Function: These four annotations are used on the interface to realize the development of annotations and realize simple addition, deletion , modification and check operations (complex SQL statements are recommended to use xml configuration files), without the use of Mapper.xml mapping file, to use these four annotations The interface is bound in the core configuration file.

@Select("select * from user")
List<User> getUsers();

@Insert("insert into user(id,name,pwd) values (#{id},#{name},#{password})")
int addUser(User user);

@Update("update user set name=#{name},pwd=#{password} where id = #{id}")
int updateUser(User user);

@Delete("delete from user where id = #{id}")
int deleteUser(int id);
<!--绑定接口-->
<mappers>
    <mapper class="com.kuang.dao.UserMapper"/>
</mappers>

3、@Param

Function: The SQL statement in the development of the mapping file and the annotation development refers to the attribute name set in the annotation. Parameters of basic data types and String types need to add this annotation, and reference types do not need to be added. If there is only one basic type, it can be ignored (it is not recommended to ignore).

// 方法存在多个参数,所有的参数前面必须加上 @Param("id")注解
@Select("select * from user where id = #{ID}")
User getUserByID(@Param("ID") int id);

4. Lombok annotation

Function: It is convenient for us to create entity classes, omitting the getter/setter methods in our entity class code , parameter construction/non-parameter construction and other methods .

Steps for usage:

  1. Install the Lombok plugin in Idea
  2. Import the lombok dependency in the maven project
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.18.10</version>
</dependency>
  1. Add a comment on the entity class:
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
    
    
    private int id;
    private String name;
    private String pwd;
}

At this time, the structure of this class is as follows: The annotations of the Lombok plug-in make it more convenient for us to create entity classes .
Insert picture description here

Two, Spring annotation

1、@Autowired

Function: According to the data type, the beans in the ioc container are automatically assembled without manual injection.

@Autowired(required=false), if the allowed object is null, set required = false, the default is true

//使用之前需要导入 spring-aop的依赖!
public class User {
    
    
	//不需要set方法!
   @Autowired
   private Cat cat;
   @Autowired
   private Dog dog;
}

2, @ qualiîas

Function: @Autowired is automatically assembled according to the type, and @Qualifier can be automatically assembled according to byName(id). @Qualifier cannot be used alone.

@Autowired
@Qualifier(value = "cat2")
private Cat cat;
@Autowired
@Qualifier(value = "dog2")
private Dog dog;

3、@Resource

Function: If @Resource has the specified name attribute, first find and assemble byName according to this attribute; if it is unsuccessful, it will automatically assemble according to byType. ( Contrary to Autowired and Qualifier annotations )

public class User {
    
    
   //如果允许对象为null,设置required = false,默认为true
   @Resource(name = "cat2")
   private Cat cat;
   @Resource
   private Dog dog;
}

4、@Component & @Value

Role: to automatically register the entity class to the ioc container to manage the assembly . It can be used with the @Value annotation. You need to scan the package of the entity class before using the annotation.

<context:component-scan base-package="com.xu.pojo"/>
@Component("user") //将这个类标注为Spring的一个组件,放到容器中!
// 相当于配置文件中 <bean id="user" class="当前注解的类"/>
public class User {
    
    
   @Value("Coder Xu")//可以不提供set方法直接使用,也可以声明在set方法上
   // 相当于配置文件中 <property name="name" value="Coder Xu"/>
   private String name;
}

5、@Controller、@Service、@Repository

Function: @Component three derivative annotations, in order to better layer, you can use these three annotations, the function is the same as @Component. Writing these annotations is equivalent to handing over this class to Spring to manage the assembly ! It is also necessary to scan the package of the entity class before using this annotation.

  • @Controller: web layer
  • @Service: service layer
  • @Repository: dao layers
@Controller("user")
public class User {
    
    
   @Value("徐志斌")
   private String name;
}

6、@Configuration & @Bean

Role: Provide Bean definition information through Java classes.

//新建一个config配置包,编写一个MyConfig配置类

@Configuration  //代表这是一个配置类
public class MyConfig {
    
    
   @Bean //通过方法注册一个bean,这里的返回值就Bean的类型,方法名就是bean的id!
   public Dog dog(){
    
    
       return new Dog();
  }
}

7、@Import

Role: Declare on the class of the component in the container to automatically create the component for the container

@Configuration
@Import(MyConfig2.class)  
public class MyConfig {
    
    
   @Bean
   public Dog dog(){
    
    
       return new Dog();
  }
}

Three, SpringMVC annotations

1、@Controller

Function: Used to declare that the instance of the Spring class is a controller (the other 3 annotations are mentioned when talking about IOC), Spring can use the scanning mechanism to find all annotation-based controller classes in the application.

In order to ensure that Spring can find your controller, you need to declare component scanning in the configuration file.

<!-- 自动扫描指定的包,下面所有注解类交给IOC容器管理 -->
<context:component-scan base-package="com.xu.controller"/>
//@Controller注解的类会自动添加到Spring上下文中
@Controller
public class ControllerTest2{
    
    
   //映射访问路径
   @RequestMapping("/t2")
   public String index(Model model){
    
    
       //Spring MVC会自动实例化一个Model对象用于向视图中传值
       model.addAttribute("msg", "ControllerTest2");
       //返回视图位置
       return "test";
  }
}

2、@RequestMapping

Function: Map the request path, the annotation will respond when the browser sends the request

@Controller
@RequestMapping("/HelloController")
public class HelloController {
    
    
   //真实访问地址 : 项目名/HelloController/hello
   @RequestMapping("/hello")
   public String sayHello(Model model){
    
    
     
   }
}

3 、 @ PathVariable

Function: Let the value of the method parameter be bound to a URI template variable. Generally used in RestFul style.

@Controller
public class RestFulController {
    
    
   //映射访问路径
   @RequestMapping("/commit/{p1}/{p2}")
   public String index(@PathVariable int p1, @PathVariable int p2, Model model){
    
    
       int result = p1+p2;
       //Spring MVC会自动实例化一个Model对象用于向视图中传值
       model.addAttribute("msg", "结果:"+result);
       //返回视图位置
       return "test";       
  }   
}

输入网址:http://localhost:8080/commit/1/2访问
页面显示: 结果:3

4、 @ResponseBody

Function: Using this annotation will not cause a view jump (without going through the view parser), and directly return the string to the page.

@Controller
public class UserController {
    
    
   @RequestMapping("/test")
   @ResponseBody
   public String test(){
    
    
       return str;
  }
}

5、@RestController

Function: Use @RestController directly on the class, so that all methods in it will only return strings, and there is no need to add @ResponseBody to each one! We generally use @RestController in the development of front-end and back-end separation, which is very convenient!

@RestController
public class UserController {
    
    
   @RequestMapping("/test")
   public String test(){
    
    
       return str;
  }
}

Four, SpringBoot annotations

1、@SpringBootApplication

Role: springboot application indicates that this is a general statement of the main program on

/**
 * 主程序类
 * @SpringBootApplication:这是一个SpringBoot应用
 */
@SpringBootApplication
public class MainApplication {
    
    

    public static void main(String[] args) {
    
    
        SpringApplication.run(MainApplication.class,args);
    }
}
//该注解等同于以下三个注解组合
@SpringBootApplication
public class SpringBootApplication{
    
    
}

等同于
//这三个注解后面后讲解
@SpringBootConfiguration
@EnableAutoConfiguration
@ComponentScan("com.xu.boot")
public class SpringBootApplication{
    
    
}

2、@Configuration & @Bean

Role: Tell SpringBoot this is a configuration class (no need to manually register in the ioc container)

/**
 * 1、配置类里面使用@Bean标注在方法上给容器注册组件,默认也是单实例的
 * 2、@Configuration标注的配置类本身就是一个组件
 * 3、proxyBeanMethods:代理bean的方法
 * 
 * Full(proxyBeanMethods = true)
 * 【保证每个@Bean方法被调用多少次返回的组件都是单实例的】
 * 
 * Lite(proxyBeanMethods = false)
 * 【每个@Bean方法被调用多少次返回的组件都是新创建的】
 * 
 * 组件依赖必须使用Full模式默认。其他默认是否Lite模式
 */
@Configuration(proxyBeanMethods = false) //告诉SpringBoot这是一个配置类 
public class MyConfig {
    
    
    /**
     * Full:外部无论对配置类中的这个组件注册方法调用多少次获取的都是之前注	  册容器中的单实例对象
     */
    @Bean //给容器中添加组件。以方法名作为组件的id。返回类型就是组件类型。返回的值,就是组件在容器中的实例
    public User user01(){
    
    
        User zhangsan = new User("zhangsan", 18);
    }

    @Bean("tom") //自定义组件id名为tom
    public Pet tomcatPet(){
    
    
        return new Pet("tomcat");
    }
}

3、@Import

Role: Declare on the class of the component in the container to automatically create the component for the container

//给容器中自动创建出这两个类型的组件,默认组件的名字就是全类名
@Import({
    
    User.class, DBHelper.class})
//告诉SpringBoot这是一个配置类 == 配置文件
@Configuration(proxyBeanMethods = false) 
public class MyConfig {
    
    

}

4、@Conditional

Function: Conditional assembly . If the conditions specified by Conditional are met, component injection will be carried out. This is a root annotation , which has a lot of sub-annotations derived, and can be used reasonably according to the actual situation.
Insert picture description here

@Configuration(proxyBeanMethods = true) //告诉Springboot这是一个配置类 == ioc配置文件
//@ConditionalOnBean(name = "tom")
@ConditionalOnMissingBean(name = "tom")
public class MyConfig {
    
    
    @Bean
    public User user01(){
    
    
        User zhangsan = new User("zhangsan",18);
        //user组件依赖Pet组件
        zhangsan.setPet(tomcatPet());
        return zhangsan;
    }

    @Bean("tom") //自定义组件id名为tom
    public Pet tomcatPet(){
    
    
        return new Pet("Tomcat");
    }
}

5、@Component、@Controller、@Service、@Repository

这几个注解在  Spring注解部分  提到过,这里不再过多叙述!

6、@ImportResource

Function: Our SpringBoot program cannot recognize the ioc configuration file. The function of this annotation is to import Spring's ioc configuration file in the SpringBoot project .

@ImportResource("classpath:beans.xml")
public class MyConfig {
    
    

}

7、@ConfigurationProperties & @EnableConfigurationProperties

Function: Configure binding with SpringBoot core configuration file (application.properties) !

The first method :

@Component  //只有在容器中的组件,才会拥有SpringBoot提供的强大功能(比如注解)
@ConfigurationProperties(prefix = "mycar")
public class Car {
    
    
    private String brand;
    private Integer price;

    //getter + setter
}

In the SpringBoot configuration file application.properties:

mycar.brand=BYD
mycar.price=100000

The second method:

@Configuration
@EnableConfigurationProperties(Car.class)
//1、开启Car配置绑定功能
//2、把这个Car这个组件自动注册到容器中
public class MyConfig {
    
    

}

//这时候,Car类中就不需要@Component注解
========================================================
@ConfigurationProperties(prefix = "mycar")
public class Car {
    
    
    private String brand;
    private Integer price;

    //getter + setter
}

Note: Sometimes, we will refer to classes in third-party libraries for configuration binding. At this time, we cannot add @Component annotations to the class, so the second method is recommended for configuration binding at this time!

8、@SpringBootConfiguration

Function: The same as @Configuration function and usage, it means that the current class is a configuration class , indicating that our main program is also a configuration class!

//这三个注解一般组合出现,等同于@SpringBootApplication
@SpringBootConfiguration
//@EnableAutoConfiguration
//@ComponentScan("com.xu.boot")
public class SpringBootApplication{
    
    
}

9、@ComponentScan

Role: specify which packages we want to scan

//这三个注解一般组合出现,等同于@SpringBootApplication
//@SpringBootConfiguration
//@EnableAutoConfiguration
@ComponentScan("com.xu.boot")
public class SpringBootApplication{
    
    
}

10、@EnableAutoConfiguration

Role: Automatically import configuration

//这三个注解一般组合出现,等同于@SpringBootApplication
//@SpringBootConfiguration
@EnableAutoConfiguration
//@ComponentScan("com.xu.boot")
public class SpringBootApplication{
    
    
}

11、@AutoConfigurationPackage

Function: The sub-annotation of @EnableAutoConfiguration imports all components under the package of the main program into the container, which is why our default package path is the package where the main program is located

//利用Registrar给容器中导入一系列组件
//将指定的一个包下的所有组件导入进来?主程序类 所在包下。

//给容器中导入一个组件
@Import(AutoConfigurationPackages.Registrar.class)  
public @interface AutoConfigurationPackage {
    
    
}

12、@Import(AutoConfigurationImportSelector.class)

Function: @EnableAutoConfiguration sub-annotation, batch import some components ( 127 automatic configuration classes ) into the container, get all the configuration classes that need to be imported into the container, and use factory loading to get all the components

//@Target({ElementType.TYPE})
//@Retention(RetentionPolicy.RUNTIME)
//@Documented
//@Inherited
//@AutoConfigurationPackage
@Import({
    
    AutoConfigurationImportSelector.class})
public @interface EnableAutoConfiguration {
    
    
    String ENABLED_OVERRIDE_PROPERTY = "spring.boot.enableautoconfiguration";

    Class<?>[] exclude() default {
    
    };

    String[] excludeName() default {
    
    };
}

Guess you like

Origin blog.csdn.net/weixin_46594796/article/details/112390306