Home Java javaTutorial Summarize some of the most commonly used annotations in Java

Summarize some of the most commonly used annotations in Java

May 16, 2017 am 09:42 AM
boot spring Common annotations annotation

This article mainly introduces a summary of the common annotations used in spring boot. Friends who need it can refer to the

@RestController and @RequestMapping annotations

4.0 Important A new improvement is the @RestController annotation, which inherits from the @Controller annotation. Before version 4.0, Spring MVC components all used @Controller to identify the current class as a controllerservlet. Using this feature, we can develop REST services without using @Controller but a dedicated @RestController.

When you implement a RESTful web service, the response will always be sent through the response body. To simplify development, Spring 4.0 provides a specialized version of the controller. Let's take a look at the definition of @RestController implementation:

@Target(value=TYPE)  
 @Retention(value=RUNTIME)  
 @Documented  
 @Controller  
 @ResponseBody  
public @interface RestController  
@Target(value=TYPE) 
 @Retention(value=RUNTIME) 
 @Documented 
 @Controller 
 @ResponseBody 
public @interface RestController
Copy after login

@RequestMapping annotation provides routing information. It tells Spring that any HTTP request coming from the "/" path should be mapped to the home method. The @RestController annotation tells Spring to render the result as a string and return it directly to the caller.

Note: @RestController and @RequestMapping annotations are Spring MVC annotations (they are not specific parts of Spring Boot)

@EnableAutoConfiguration annotations

The second class-level annotation is @EnableAutoConfiguration. This annotation tells Spring Boot to guess how you want to configure Spring based on the added jar dependencies. Since spring-boot-starter-web adds Tomcat and Spring MVC, auto-configuration will assume that you are developing a web application and set up Spring accordingly. Starter POMs and Auto-Configuration: The purpose of designing auto-configuration is to make better use of "Starter POMs", but the two concepts are not directly related. You are free to choose jar dependencies outside of the starter POMs, and Spring Boot will still do its best to automatically configure your application.

You can choose automatic configuration by adding the @EnableAutoConfiguration or @SpringBootApplication annotation to a @Configuration class.

Note: You only need to add an @EnableAutoConfiguration annotation. We recommend that you add it to the main @Configuration class.

If you find that specific auto-configuration classes are applied that you don't want, you can use the exclude attribute of the @EnableAutoConfiguration annotation to disable them.

<pre name="code" class="java">import org.springframework.boot.autoconfigure.*; 
import org.springframework.boot.autoconfigure.jdbc.*; 
import org.springframework.context.annotation.*; 
@Configuration 
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class}) 
public class MyConfiguration { 
} 
<pre name="code" class="java">import org.springframework.boot.autoconfigure.*;
import org.springframework.boot.autoconfigure.jdbc.*;
import org.springframework.context.annotation.*;
@Configuration
@EnableAutoConfiguration(exclude={DataSourceAutoConfiguration.class})
public class MyConfiguration {
}
@Configuration
Copy after login

Spring Boot advocates Java-based configuration. Although you can use an XML source to call SpringApplication.run(), we generally recommend that you use a @Configuration class as the primary source. Classes that generally define a main method are also a good candidate for the main @Configuration. You don't need to put all @Configuration into a single class. The @Import annotation can be used to import other configuration classes. Alternatively, you can use the @ComponentScan annotation to automatically collect all Spring components, including @Configuration classes.

If you absolutely need to use XML-based configuration, we recommend that you still start with a @Configuration class. You can load XMLconfiguration files using the additional @ImportResource annotation.

@Configuration annotation of this class is equivalent to configuring beans in XML; using @Bean annotation method is equivalent to configuring beans in XML

@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)}) 
@ComponentScan(basePackages = "com.hyxt",includeFilters = {@ComponentScan.Filter(Aspect.class)})
@SpringBootApplication
Copy after login

Many Spring Boot developers always use @Configuration, @EnableAutoConfiguration and @ComponentScan annotate their main classes. Since these annotations are used together so frequently (especially if you follow the best practices above), Spring Boot provides a convenient @SpringBootApplication alternative.

The @SpringBootApplication annotation is equivalent to using @Configuration, @EnableAutoConfiguration and @ComponentScan with default properties.

package com.example.myproject; 
import org.springframework.boot.SpringApplication; 
import org.springframework.boot.autoconfigure.SpringBootApplication; 
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan  
public class Application { 
  public static void main(String[] args) { 
    SpringApplication.run(Application.class, args); 
  } 
} 
package com.example.myproject;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication // same as @Configuration @EnableAutoConfiguration @ComponentScan
public class Application {
  public static void main(String[] args) {
    SpringApplication.run(Application.class, args);
  }
}
Copy after login

Spring Boot will try to verify external configuration, using JSR-303 by default (if it is in the classpath). You can easily add JSR-303 javax.validationconstraints to your @ConfigurationProperties class. Annotation:

@Component 
@ConfigurationProperties(prefix="connection") 
public class ConnectionSettings { 
@NotNull 
private InetAddress remoteAddress; 
// ... getters and setters  
} 
@Component
@ConfigurationProperties(prefix="connection")
public class ConnectionSettings {
@NotNull
private InetAddress remoteAddress;
// ... getters and setters
}
@Profiles
Spring Profiles提供了一种隔离应用程序配置的方式,并让这些配置只能在特定的环境下生效。任何@Component或@Configuration都能被@Profile标记,从而限制加载它的时机。
[java] view plain copy print?在CODE上查看代码片派生到我的代码片
@Configuration 
@Profile("production") 
public class ProductionConfiguration { 
// ...  
} 
@Configuration
@Profile("production")
public class ProductionConfiguration {
// ...
}@ResponseBody
Copy after login

indicates that the return result of this method is written directly into the HTTP response body

Generally used when obtaining data asynchronously. After using @RequestMapping, the return value is usually parsed as a jump path. After adding

@responsebody, the return result will not be parsed as a jump path, but directly Written into the HTTP response body. For example,
asynchronously obtains json data, and after adding @responsebody, json data will be returned directly.

@Component:

泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。一般公共的方法我会用上这个注解

@AutoWired

byType方式。把配置好的Bean拿来用,完成属性、方法的组装,它可以对类成员变量、方法及构
函数进行标注,完成自动装配的工作。

当加上(required=false)时,就算找不到bean也不报错。

@RequestParam:

用在方法的参数前面。

@RequestParam String a =request.getParameter("a")。 
@RequestParam String a =request.getParameter("a")。
Copy after login

@PathVariable:

路径变量。

RequestMapping("user/get/mac/{macAddress}") 
public String getByMacAddress(@PathVariable String macAddress){ 
//do something;  
} 
RequestMapping("user/get/mac/{macAddress}")
public String getByMacAddress(@PathVariable String macAddress){
//do something;
}
Copy after login

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

以上注解的示范

/** 
 * 用户进行评论及对评论进行管理的 Controller 类; 
 */ 
@Controller 
@RequestMapping("/msgCenter") 
public class MyCommentController extends BaseController { 
  @Autowired 
  CommentService commentService; 
  @Autowired 
  OperatorService operatorService; 
  /** 
   * 添加活动评论; 
   * 
   * @param applyId 活动 ID; 
   * @param content 评论内容; 
   * @return 
   */ 
  @ResponseBody 
  @RequestMapping("/addComment") 
  public Map<String, Object> addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) { 
    .... 
    return result; 
  } 
} 
/**
 * 用户进行评论及对评论进行管理的 Controller 类;
 */
@Controller
@RequestMapping("/msgCenter")
public class MyCommentController extends BaseController {
  @Autowired
  CommentService commentService;
  @Autowired
  OperatorService operatorService;
  /**
   * 添加活动评论;
   *
   * @param applyId 活动 ID;
   * @param content 评论内容;
   * @return
   */
  @ResponseBody
  @RequestMapping("/addComment")
  public Map<String, Object> addComment(@RequestParam("applyId") Integer applyId, @RequestParam("content") String content) {
    ....
    return result;
  }
}
@RequestMapping("/list/{applyId}") 
  public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) { 
} 
 @RequestMapping("/list/{applyId}")
  public String list(@PathVariable Long applyId, HttpServletRequest request, ModelMap modelMap) {
}
Copy after login

全局处理异常的:

@ControllerAdvice:

包含@Component。可以被扫描到。

统一处理异常。

@ExceptionHandler(Exception.class):

用在方法上面表示遇到这个异常就执行以下方法。

/** 
 * 全局异常处理 
 */ 
@ControllerAdvice 
class GlobalDefaultExceptionHandler { 
  public static final String DEFAULT_ERROR_VIEW = "error"; 
  @ExceptionHandler({TypeMismatchException.class,NumberFormatException.class}) 
  public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception { 
    ModelAndView mav = new ModelAndView(); 
    mav.addObject("error","参数类型错误"); 
    mav.addObject("exception", e); 
    mav.addObject("url", RequestUtils.getCompleteRequestUrl(req)); 
    mav.addObject("timestamp", new Date()); 
    mav.setViewName(DEFAULT_ERROR_VIEW); 
    return mav; 
  }} 
/**
 * 全局异常处理
 */
@ControllerAdvice
class GlobalDefaultExceptionHandler {
  public static final String DEFAULT_ERROR_VIEW = "error";
  @ExceptionHandler({TypeMismatchException.class,NumberFormatException.class})
  public ModelAndView formatErrorHandler(HttpServletRequest req, Exception e) throws Exception {
    ModelAndView mav = new ModelAndView();
    mav.addObject("error","参数类型错误");
    mav.addObject("exception", e);
    mav.addObject("url", RequestUtils.getCompleteRequestUrl(req));
    mav.addObject("timestamp", new Date());
    mav.setViewName(DEFAULT_ERROR_VIEW);
    return mav;
  }}
Copy after login

通过@value注解来读取application.properties里面的配置

# face++ key 
face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR**** 
face_api_secret =D9WUQGCYLvOCIdsbX35uTH******** 
# face++ key
face_api_key = R9Z3Vxc7ZcxfewgVrjOyrvu1d-qR****
face_api_secret =D9WUQGCYLvOCIdsbX35uTH********
@Value("${face_api_key}") 
  private String API_KEY; 
  @Value("${face_api_secret}") 
  private String API_SECRET; 
 @Value("${face_api_key}")
  private String API_KEY;
  @Value("${face_api_secret}")
  private String API_SECRET;所以一般常用的配置都是配置在application.properties文件的
Copy after login

【相关推荐】

1. 特别推荐“php程序员工具箱”V0.1版本下载

2. Java免费视频教程

3. JAVA教程手册

The above is the detailed content of Summarize some of the most commonly used annotations in Java. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Windows ISO file too large BootCamp error [Fixed] Windows ISO file too large BootCamp error [Fixed] Feb 19, 2024 pm 12:30 PM

Windows ISO file too large BootCamp error [Fixed]

What are the implementation methods of spring programmatic transactions? What are the implementation methods of spring programmatic transactions? Jan 08, 2024 am 10:23 AM

What are the implementation methods of spring programmatic transactions?

A new programming paradigm, when Spring Boot meets OpenAI A new programming paradigm, when Spring Boot meets OpenAI Feb 01, 2024 pm 09:18 PM

A new programming paradigm, when Spring Boot meets OpenAI

Use Spring Boot and Spring AI to build generative artificial intelligence applications Use Spring Boot and Spring AI to build generative artificial intelligence applications Apr 28, 2024 am 11:46 AM

Use Spring Boot and Spring AI to build generative artificial intelligence applications

The King of PHP Code Documentation: An Advanced Guide to PHPDoc The King of PHP Code Documentation: An Advanced Guide to PHPDoc Mar 02, 2024 am 08:43 AM

The King of PHP Code Documentation: An Advanced Guide to PHPDoc

How are annotations used for test methods in the JUnit framework? How are annotations used for test methods in the JUnit framework? May 06, 2024 pm 05:33 PM

How are annotations used for test methods in the JUnit framework?

How do annotations in the Jackson library control JSON serialization and deserialization? How do annotations in the Jackson library control JSON serialization and deserialization? May 06, 2024 pm 10:09 PM

How do annotations in the Jackson library control JSON serialization and deserialization?

Detailed explanation of the operation steps of MyBatis annotations and dynamic SQL Detailed explanation of the operation steps of MyBatis annotations and dynamic SQL Feb 18, 2024 pm 03:29 PM

Detailed explanation of the operation steps of MyBatis annotations and dynamic SQL

See all articles