Detailed analysis of 36 spring-boot annotations, clear at a glance

 

1.@Component

Function and scope: Loading the object into the spring container, the most basic existence, many annotations are inherited from it, there is only one attribute value, the default value is "",

Example or source code:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Indexed
public @interface Component {

 String value() default "";

}

2.@Service

Function and scope: It is generally used for the annotations of the service layer, inheriting the Component component, which is essentially the same, and it is convenient to distinguish the business scope.

Example or source code:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Service {

 @AliasFor(annotation = Component.class)
 String value() default "";

}

3.@Repository

Function and scope: the annotations that act on the dao layer. Many students who often use JPA know this thing. It is essentially the same as the service, but it is different in the business field.

Example or source code:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Repository {

 @AliasFor(annotation = Component.class)
 String value() default "";

}

4.@Controller

Function and scope: The annotations acting on the controller, like Service, are distinguished by business areas

Example or source code:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {

 @AliasFor(annotation = Component.class)
 String value() default "";

}

5.@Autowired

Function and scope: It can mark class member variables, methods and constructors to complete the work of automatic assembly. In fact, it is to obtain the objects in the container

Precautions:

When using @Autowired, first query the corresponding type of bean in the container

If the query result happens to be one, the bean is assembled to the data specified by @Autowired

If there is more than one result of the query, @Autowired will search by name.

If the result of the query is empty, an exception will be thrown. When solving, use required=false

Example or source code:

@Target({ElementType.CONSTRUCTOR, ElementType.METHOD, ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {

 boolean required() default true;

}

6.@Inject

Function and scope: It is a specification in JSR330 (Dependency Injection for Java), which needs to be imported into javax.inject.Inject; to realize injection, automatic assembly according to the type, if you need to assemble by name, you need to cooperate with @Named, which can be used On variables, setter methods, and constructors. seldom use it

Example or source code:

@Inject
public Message(Header header, Content content)
{
    this.headr = header;
    this.content = content;
}
public class Messager
{
    @Inject
    private Message message;
}

7.@Resource

Function and scope: It is the implementation of the JSR250 specification. It also needs to import javax.annotation to achieve injection. It is automatically assembled based on the name. Generally, a name attribute is specified, which can be used on variables and setter methods.

Example or source code:

@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
@Repeatable(Resources.class)
public @interface Resource {

    String name() default "";
  
    String lookup() default "";

    Class<?> type() default java.lang.Object.class;

    enum AuthenticationType {
     CONTAINER,
     APPLICATION
    }

    AuthenticationType authenticationType() default AuthenticationType.CONTAINER;

    boolean shareable() default true;

    String mappedName() default "";

    String description() default "";
}

8.@Configuration

Function and scope: From Spring 3.0, @Configuration is used to define configuration classes and can replace xml configuration files. The annotated class contains one or more methods annotated by @Bean, as well as the most primitive annotation Component in AliasFor

Example or source code:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Configuration {

 @AliasFor(annotation = Component.class)
 String value() default "";

 boolean proxyBeanMethods() default true;

}

9.@Bean

Function and scope: Act on the method to generate an object, and then this object is handed over to Spring for management. During the initialization process, it will only be generated and called once. If the container manages one or more beans, these beans need to be in the Configuration Create under annotations. Using Bean annotations on a method indicates that this method needs to be handed over to Spring for management.

Example or source code:

@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {

 @AliasFor("name")
 String[] value() default {};

 @AliasFor("value")
 String[] name() default {};

 Autowire autowire() default Autowire.NO;

 String initMethod() default "";

 String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;

}

10.@ComponentScan

Function and scope: Scan all objects under the current class. Why is Component the most basic thing? It is to scan this annotation. It is very cleverly designed and can scan multiple packages.

Example or source code:

@ComponentScan(“com.abc.aaa”)
@SpringBootApplication
public class SpringbootApplication {
@ComponentScan({"com.abc.bbb","com.abc.aaa"})
@SpringBootApplication
public class SpringbootApplication {

11.@WishlyConfiguration

Function and scope: This is a combined annotation of Configuration and ComponentScan, which can replace these two annotations, and is currently very rarely used.

Example or source code: never used

12.@Aspect

Function and scope: section annotations, which are often used in section programming, can be used as a log

Example or source code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Aspect {

    public String value() default "";
}

13.@After

Function and scope: Configure Aspect for aspect use, and execute after method execution (on method)

Example or source code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface After {

    String value();
    
    String argNames() default "";
}

14.@Before

Function and scope: Configure Aspect for aspect use, and execute before method execution (on method)

Example or source code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Before {

    String value();
    
    String argNames() default "";

}

15.@Around

Function and scope: configure Aspect for aspect use, execute before and after method execution (on method)

Example or source code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Around {

    String value();
    
    String argNames() default "";

}

16.@PointCut

Function and scope: configure Aspect for aspect use, declare point of cut

Example or source code:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
public @interface Pointcut {
  
    String value() default "";
    
    String argNames() default "";
}

17.@Scope

Role and scope: Singleton (singleton, there is only one bean instance in a Spring container, the default mode),

Protetype (create a new bean for each call),

Request (in the web project, create a bean for each http request),

Session (in the web project, create a bean for each http session),

GlobalSession (create a Bean instance for each global http session)

Example or source code:

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

 @AliasFor("scopeName")
 String value() default "";

 @AliasFor("value")
 String scopeName() default "";

 ScopedProxyMode proxyMode() default ScopedProxyMode.DEFAULT;

}

18.@Value

Function and scope: Dynamically inject external values ​​into the Bean, the use cases are as follows:

  • Inject ordinary strings

  • Inject operating system properties

  • Inject expression result

  • Inject other bean properties: inject the properties of the beanInject object another

  • Inject file resources

  • Inject URL resources

Example or source code:

   @Value("normal")
    private String normal; // 注入普通字符串

    @Value("#{systemProperties['os.name']}")
    private String systemPropertiesName; // 注入操作系统属性

    @Value("#{ T(java.lang.Math).random() * 100.0 }")
    private double randomNumber; //注入表达式结果

    @Value("#{beanInject.another}")
    private String fromAnotherBean; // 注入其他Bean属性:注入beanInject对象的属性another,类具体定义见下面

    @Value("classpath:com/hry/spring/configinject/config.txt")
    private Resource resourceFile; // 注入文件资源

    @Value("http://www.baidu.com")
    private Resource testUrl; // 注入URL资源

19.@PropertySource

Function and scope: load the specified configuration file

Example or source code:

@PropertySource(value = {"classpath:test.properties"})
@Component
@ConfigurationProperties(prefix = "test")
public class Test {
    private Integer id;
    private String lastName;
}

20.@Profile

Function and scope: load bean objects according to different environments

Example or source code:

@PropertySource("classpath:/user.properties")
@Configuration
public class MainConfigOfProfile implements EmbeddedValueResolverAware{
 
 @Profile("test")
 @Bean("testUser")
 public User testUser()  {
  User a =new User();
    return a;
 }
 
 @Profile("dev")
 @Bean("devUser")
 public User devUser()  {
  User a =new User();
    return a;
 }
 
}

21.@Conditional

Function and scope: It is a new annotation provided by Spring4. Its function is to judge according to certain conditions and register beans to the container when the conditions are met.

Example or source code:

@Configuration
public class BeanConfig {
 
    //只有一个类时,大括号可以省略
    //如果WindowsCondition的实现方法返回true,则注入这个bean    
    @Conditional({WindowsCondition.class})
    @Bean(name = "bill")
    public Window window(){
        return new Window();
    }
 
    //如果LinuxCondition的实现方法返回true,则注入这个bean
    @Conditional({LinuxCondition.class})
    @Bean("linux")
    public Linex linux(){
        return new Linex();
    }
}

22.@EnableAsync

Function and scope: start asynchronous, use in conjunction with Async

Example or source code:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Import(AsyncConfigurationSelector.class)
public @interface EnableAsync {

 Class<? extends Annotation> annotation() default Annotation.class;

 boolean proxyTargetClass() default false;

 AdviceMode mode() default AdviceMode.PROXY;

 int order() default Ordered.LOWEST_PRECEDENCE;

}

23.@Async

Function and scope: asynchronous annotation, need to be used in conjunction with EnableAsync, after use, the method becomes an asynchronous method

Example or source code:

@Component
public class TreadTasks {
    @Async
    public void startMyTreadTask() {
        System.out.println("this is my async task");
    }
}

24.@EnableScheduling

Function and scope: Timed task annotation scanner, which will scan all timed tasks under the package body

Example or source code:

@SpringBootApplication
@EnableScheduling //开启定时任务
public class MainApplication {

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

25.@Scheduled

Function and scope: timing task controller

Example or source code:

@Scheduled(cron = "0 0 2 * * ?") 

26.@EnableJpaRepositories

Role and scope: open support for SpringData JPA Repository

Example or source code:

@EnableJpaRepositories({"com.cshtong.sample.repository", "com.cshtong.tower.repository"})

27.@EnableTransactionManagement

Role and scope: open the support of annotated transactions

Examples or source code: the most common things, not explained

@EnableTransactionManagement // 启注解事务管理
@SpringBootApplication
public class ProfiledemoApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(ProfiledemoApplication.class, args);
    }

28.@EnableCaching

Role and scope: enable annotation-style caching support

Example or source code:

@Configuration
@EnableCaching
public class CachingConfig {

    @Bean
    public CacheManager cacheManager() {
        SimpleCacheManager cacheManager = new SimpleCacheManager();
        cacheManager.setCaches(Arrays.asList(new ConcurrentMapCache("sampleCache")));
        return cacheManager;
    }
}

29.@Cacheable

Function and scope: put information in storage

Example or source code:

@Cacheable(value = { "sampleCache","sampleCache2" },key="targetClass.getName()+'.'+methodName+'.'+#id")
    public String getUser(int id) {
        if (id == 1) {
            return "1";
        } else {
            return "2";
        }
    }

30.@RequestMapping

Role and scope: annotations to map the request URL to the entire class or a specific method

Example or source code:

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

 String name() default "";

 @AliasFor("path")
 String[] value() default {};

 @AliasFor("value")
 String[] path() default {};

 RequestMethod[] method() default {};

 String[] params() default {};

 String[] headers() default {};

 String[] consumes() default {};

 String[] produces() default {};

}

31.@ResponseBody

Function and scope: After the object returned by the controller method is converted into the specified format through an appropriate converter, it is written to the body area of ​​the response object, usually used to return JSON data or XML data

Example or source code:

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

}

32.@RequestBody

Function and scope: used to receive the data in the json string passed by the front end to the back end (data in the request body)

Example or source code:

@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestBody {

 /**
  * 默认是必须的
  */
 boolean required() default true;

}

33. @ PathVariable

Function and scope: receiving the value of placeholder in the request path

Example or source code:

@RequestMapping(value=”user/{id}/{name}”)
请求路径:http://localhost:8080/user//1/james

34.@RestController

Function and scope: equivalent to @Controller + @ResponseBody

Example or source code:

@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {

 @AliasFor(annotation = Controller.class)
 String value() default "";

}

35. @ ControllerAdvice

Function and scope: global exception handling; global data binding; global data preprocessing

Example or source code:

@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ExceptionHandler(Exception.class)
    public ModelAndView customException(Exception e) {
        ModelAndView mv = new ModelAndView();
        mv.addObject("message", e.getMessage());
        mv.setViewName("error");
        return mv;
    }
}

@ControllerAdvice
public class MyGlobalExceptionHandler {
    @ModelAttribute(name = "md")
    public Map<String,Object> mydata() {
        HashMap<String, Object> map = new HashMap<>();
        map.put("gender", "女");
        return map;
    }
}

36.@ExceptionHandler

Role and scope: used to handle exceptions at the controller level

Example or source code:

 @ExceptionHandler({RuntimeException.class})
    public ModelAndView fix(Exception ex){
        System.out.println("aaaa");
        return new ModelAndView("error",new ModelMap("ex",ex.getMessage()));
    }

Guess you like

Origin blog.csdn.net/qq_31905135/article/details/107908962