Springboot use annotations summary

Use Spring boot has been for some time, but with many annotations will always be blurred even understand the place, this time there will sum up.

Annotation (Annotation) concept

Annotations are beginning Java5 support for metadata, annotations and comments are quite different, and can be understood as a code annotated with special markers that can be compiled, the class is loaded, the runtime is read, and perform the appropriate deal with. These marks can be seen as a template for a class or a method of expansion of each class or method in accordance with the rules of the class notes, annotate different parameters for the class or method, you can get different classes used in place or values ​​of various parameters and process annotations.

Java which offers five basic notes:

@Override: override methods defined in the parent class. When a subclass overrides the parent class method, subclasses can add this comment, what good does it with what? This ensures that a subclass does override the parent class method to avoid low-level errors.

@Deprecated: marked obsolete. This annotation is used to represent a class of program elements and methods obsolete when other programs that use deprecated classes, methods, the compiler will give a warning.

@SuppressWarnings: suppress compiler warnings. The show was canceled annotation modified element and all child elements of compiler warnings, such as modifying a class, and that his field, methods are no warning.

@SafeVarargs: inhibition heap pollution warning. Fuzzy type in a statement: when a constructor method or variable parameters (such as generics) is, Java compiler will report unchecked warning. Given these circumstances, if the programmer to determine the main constructors and methods of declaration does not perform its operations potentially unsafe varargs parameters can be used @SafeVarargs marked, so, Java compiler will not report unchecked warning.

@FunctionalInterface: functional interface. If the interface is only an abstract method (default method may comprise a plurality of more or static method), only the interface body and abstract method declarations constant fields, and is implicitly declared as public, static, final, proprietary interfaces can not have inside method or variable. This annotation interface to ensure that this is only an abstract method, note that this can only be modified interface.

Annotation (Annotation) Comments

@SpringBootApplication:

Disclaimer let spring boot automatically makes the necessary configuration to the program, this configuration is equivalent to: @Configuration, @ EnableAutoConfiguration and @ComponentScan three configurations:

 

@SpringBootApplication 
public class ApplicationMain { 
    public static void main(String[] args) { 
        SpringApplication.run(Application.class, args); 
    } 
}

@Configuration: @Configuration mentioned we should mention his partner @Bean. These two notes can create a simple spring configuration class can be used to replace the corresponding xml configuration files.

<beans> 
    <bean id = "car" class="com.test.Car"> 
        <property name="wheel" ref = "wheel"></property> 
    </bean> 
    <bean id = "wheel" class="com.test.Wheel"></bean> 
</beans> 

Equivalent to

@Configuration 
public class Conf { 
    @Bean 
    public Car car() { 
        Car car = new Car(); 
        car.setWheel(wheel()); 
        return car; 
    } 
    @Bean  
    public Wheel wheel() { 
        return new Wheel(); 
    } 
}

@Configuration annotation identifies the class type may be used as a source Spring IoC container bean definition. @Bean annotation tells Spring, with a @Bean annotation method returns an object that should be registered as a bean in the Spring application context. As if some third-party libraries need to use xml file, still recommended by @Configuration class as the main class configuration items - can be used to load xml configuration file @ImportResource comment.

@EnableAutoConfiguration: Spring Boot automatic configuration (auto-configuration): attempts to automatically configure your Spring application according to jar you depend added. For example, if your classpath under HSQLDB, and you do not have to manually configure any database connections beans, then we will automatically configure a type of memory (in-memory) database. "You can add notes to a @EnableAutoConfiguration or @SpringBootApplication @Configuration class up select automatic configuration. If you find that a particular application automatically configures classes you do not want, you can use negative attributes @EnableAutoConfiguration comment to disable them.

@ComponentScan: indicates the type of automatic discovery scanning assembly. Equivalent, if the class has to scan these annotations @ Component, @ Controller, @ Service, etc., and registered as Bean, Spring can automatically collect all the components, including @Configuration class. We often use @ComponentScan annotation search beans, combined with @Autowired notes import. Spring can automatically collect all the components, including @Configuration class. We often use @ComponentScan annotation search beans, combined with @Autowired notes import. If no words, Spring Boot will start scanning the next class pack and use the @ Service, @ Repository annotation and other sub-package in the class lies.

 @RestController:

Labeling assembly for controlling layer (e.g., the action struts), @ ResponseBody @Controller and the collection, as with @Controller, together with @RequestMapping often used together. Sample code:

@RestController 
@RequestMapping(“/demoInfo2”) 
publicclass DemoController2 {

@RequestMapping("/test")
public String test(){
   return"ok";
}
}

@ResponseBody: indicates that the method returns the result directly written HTTP response body is generally used in the asynchronous data acquired for constructing the api RESTful. @RequestMapping after use, the return value is typically resolved as the jump path and, with the results returned @responsebody not be interpreted as the jump path, but directly written in the HTTP response body. Such as asynchronous get json data, after adding @responsebody, it will return json data directly. The Notes will generally be used in conjunction with @RequestMapping. Sample code:

@RequestMapping(“/test”) 
@ResponseBody 
public String test(){ 
return”ok”; 
}

  

@Controller: a controller for defining classes in the spring by the controller responsible for the project forwards the URL request sent by a user to the corresponding service interface (service layer), generally in the annotation class annotated with the conventional method requires @RequestMapping . Sample code:

@Controller 
@RequestMapping(“/demoInfo”) 
publicclass DemoController { 
@Autowired 
private DemoInfoService demoInfoService;

@RequestMapping("/hello")
public String hello(Map<String,Object> map){
   System.out.println("DemoController.hello()");
   map.put("hello","from TemplateController.helloHtml");
   //会使用hello.html或者hello.ftl模板进行渲染显示.
   return"/hello";
}
}

Other

@PropertySource:@PropertySource可以指定读取的配置文件,可以通过@Value注解获取值。

@ServletComponentScan在SpringBoot的main方法上使用@ServletComponentScan注解后,Servlet、Filter、Listener可以直接通过@WebServlet、@WebFilter、@WebListener注解自动注册,无需其他代码。

@EnableAsync:开启异步管理,简而言之就是启用多线程。

@EnableTransactionManagement:开启事务支持。

 

@Import:用来导入其他配置类。

@ImportResource:用来加载xml配置文件。

@Autowired:自动导入依赖的bean

@Service:一般用于修饰service层的组件

@Repository:使用@Repository注解可以确保DAO或者repositories提供异常转译,这个注解修饰的DAO或者repositories类会被ComponetScan发现并配置,同时也不需要为它们提供XML配置项。

@Bean:用@Bean标注方法等价于XML中配置的bean。

@Value:注入Spring boot application.properties配置的属性的值。示例代码:

@Value(value = “#{message}”) 
private String message;

@Inject:等价于默认的@Autowired,只是没有required属性;

@Component:泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。

@Bean:相当于XML中的,放在方法的上面,而不是类,意思是产生一个bean,并交给spring管理。

@AutoWired:自动导入依赖的bean。byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构造函数进行标注,完成自动装配的工作。当加上(required=false)时,就算找不到bean也不报错。

@Qualifier:当有多个同一类型的Bean时,可以用@Qualifier(“name”)来指定。与@Autowired配合使用。@Qualifier限定描述符除了能根据名字进行注入,但能进行更细粒度的控制如何选择候选者,具体使用方式如下:

@Autowired 
@Qualifier(value = “demoInfoService”) 
private DemoInfoService demoInfoService;

@Resource(name=”name”,type=”type”):没有括号内内容的话,默认byName。与@Autowired功能相同。

JPA注解

@Entity:@Table(name=”“):表明这是一个实体类。一般用于jpa这两个注解一般一块使用,但是如果表名和实体类名相同的话,@Table可以省略

@MappedSuperClass:用在确定是父类的entity上。父类的属性子类可以继承。

@NoRepositoryBean:一般用作父类的repository,有这个注解,spring不会去实例化该repository。

@Column:如果字段名与列名相同,则可以省略。

@Id:表示该属性为主键。

@GeneratedValue(strategy = GenerationType.SEQUENCE,generator = “repair_seq”):表示主键生成策略是sequence(可以为Auto、IDENTITY、native等,Auto表示可在多个数据库间切换),指定sequence的名字是repair_seq。

@SequenceGeneretor(name = “repair_seq”, sequenceName = “seq_repair”, allocationSize = 1):name为sequence的名称,以便使用,sequenceName为数据库的sequence名称,两个名称可以一致。

@Transient:表示该属性并非一个到数据库表的字段的映射,ORM框架将忽略该属性。如果一个属性并非数据库表的字段映射,就务必将其标示为@Transient,否则,ORM框架默认其注解为@Basic。@Basic(fetch=FetchType.LAZY):标记可以指定实体属性的加载方式

@JsonIgnore:作用是json序列化时将Java bean中的一些属性忽略掉,序列化和反序列化都受影响。

@JoinColumn(name=”loginId”):一对一:本表中指向另一个表的外键。一对多:另一个表指向本表的外键。

@OneToOne、@OneToMany、@ManyToOne:对应hibernate配置文件中的一对一,一对多,多对一。

SpringMVC相关注解

@RequestMapping:

@RequestMapping(“/path”)表示该控制器处理所有“/path”的UR L请求。RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。该注解有六个属性: 

params:指定request中必须包含某些参数值是,才让该方法处理。 
headers:指定request中必须包含某些指定的header值,才能让该方法处理请求。 
value:指定请求的实际地址,指定的地址可以是URI Template 模式 
method:指定请求的method类型, GET、POST、PUT、DELETE等 
consumes:指定处理请求的提交内容类型(Content-Type),如application/json,text/html; 
produces:指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回。

此外@RequestParam用在方法的参数前面。 @RequestParam String a = request.getParameter(“a”)。

@PathVariable:路径变量。如:

RequestMapping(“user/get/mac/{macAddress}”) 
public String getByMacAddress(@PathVariable String macAddress){ 
//do something; 
} 

参数与大括号里的名字一样要相同。

SpringMVC新特性

@RequestMapping有了可以替代的选项,这些选项提供了对Restful风格的支持:

@GetMapping,处理get请求 ;

@PostMapping,处理post请求 ;

@PutMapping,处理put请求 ;

@DeleteMapping,处理delete请求;

例如@PostMapping

@PostMapping(value = "/user/login")

等价于

@RequestMapping(value = "/user/login",method = RequestMethod.POST)

其他@GetMapping,@PutMapping,@DeleteMapping也是类似等价于相同的@RequestMapping请求。

全局异常处理

@ControllerAdvice:包含@Component。可以被扫描到。统一处理异常。

@ExceptionHandler(Exception.class):用在方法上面表示遇到这个异常就执行以下方法。

Guess you like

Origin www.cnblogs.com/huangwei1061047046/p/11338853.html