[Spring] Spring Annotations Daquan

table of Contents

1. What Annotations are?

2. Role Notes

3. Notes Classification

4.Spring comment

4.1, the statement notes bean

4.2, injected bean notes

4.3, java configuration or related notes

4.4, section (AOP) related annotations

4.5, provided the type comprising

4.6, @ Value Notes

4.7, context switching

4.8, asynchronous relevant

4.9, the timing of tasks related to

4.10, @ Enable * explanatory notes

4.11, test-related notes

5, SpringMVC comments

Common detailed explanation of comments


1. What Annotations are?

In fact, Java annotations or particularly common, as usual used @ Override, @ Deprecated annotation are all an expression of the way.

The official explanation for the annotation: provides a formal method for us to add information in the code so that we can very easily use these data at a later time.

 

2. Notes Role

Cleaner can write readable code to simplify repetitive tasks, such as Spring annotations;

It also provides compile-time type checking, such as foreign exchange rebate @Override when the method signature of the method is not covered by the compiler will issue an error message.

 

3. Notes Classification

  • Notes name
  • Annotation types
  • Notes action

 

There are standard annotations JDK itself provides:

  • @Override
    indicates the current method of covering method from the parent class. If you accidentally misspelled or not on the method signature, the compiler will error
  • @Deprecated
    indicates that this method has failed, will be removed in a future release
  • @SuppressWarnings
    closed compiler warnings
  • @Target
    yuan notes, indicating that the annotation is used somewhere. CONSTRUCTOR: constructor arguments FIELD: field declaration (including enum Example) LOCAL_VARIABLE: local variable declaration METHOD: method declaration PACKAGE: package declaration PARAMETER: parameter declaration TYPE: classes, interfaces (including annotations based) or enum declaration

 

4.Spring comment

spring in the configuration file when using written notes:

<?xml version="1.0" encoding="UTF-8"?>  
<span style="font-size:18px;"><beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"   
    xmlns:context="http://www.springframework.org/schema/context"  
    xmlns:aop="http://www.springframework.org/schema/aop"  
    xsi:schemaLocation="  
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd  
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd  
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
    http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.0.xsd">  
    <!--上面的内容是固定的-->
     
    <!--下面这两行就是开启扫描注解,第一行是开启扫描注解,第二行是要扫描的包位置。但是最新的Spring版本中,第一行命令合并到第二行命令中 了,也就是说可以直接写第二行--> 
    <context:annotation-config/>  
    <context:component-scan base-package="com.test" />  
</beans>

Configuration item to the configuration of the specified package scanned to dependency injection.

 

4. 1 , the statement bean notes

@Component components, there is no clear role

@Service use (service layer) Yewuluojiceng

Use @Repository (DAO layer) in the data access layer

In use @Controller presentation layer, the statement of the controller (C)

It should be noted, though temporarily Service, Repository, Conreller simply indicates where the layer of the bean, and no other role, but Spring said official documents, after these annotations will have its own unique features, so in the future try to avoid using Component common annotations.

 

4. 2 , injection bean annotations

@Autowired: provided by Spring, inject bean

@Inject: JSR-330 by

@Resource: JSR-250 by

Can comment on a set of methods and properties, recommended annotation on the property

 

4. . 3 , Java configuration class associated annotations

Current class is declared @Configuration class configuration, corresponding to the form Spring xml configuration (the type), the spring arranged in three ways, that is the third javaconfig.

@Bean annotations on the method, the method returns the current value of the statement of a bean, the alternative embodiment xml (the Method)

@Configuration declare the current class to class configuration, which combines internal @Component comments, indicating that this class is a bean (the class)

@ComponentScan ( "") for Component scan brackets write path, corresponding to the xml <CON text: Component Scan-  Base-Package = "com.test"  /> (upper class)

@WishlyConfiguration combination with @ComponentScan @Configuration annotations can replace the two annotations

 

4. . 4 , section ( the AOP ) associated annotations

Spring supports AspectJ annotation style section of programming.

@Aspect declare a section (upper class) using @ After, @ Before, @ Around defined suggestions (advice), can be directly blocking rules (cutting point) as a parameter.

@After performed after performing the method (the method)

@Before performed prior to performing the method (the method)

@Around performed before the method is performed after (the method)

@PointCut sound Mingqie point

Use @EnableAspectJAutoProxy in java class configuration support for AspectJ annotation open Spring agents (the class)

@Bean attributes support

How to create a new container is provided @Scope Spring Bean instance (the method, must have @Bean)

 

4.5 , provided the type comprising

Singleton (single embodiment, a container only a bean instance, the Spring default mode),

Protetype (each call to create a new bean),

Request (web project, every http request to create a new bean),

Session (web projects, each http session to create a new bean),

GlobalSession (to each create a new global http session Bean instance)

@StepScope also involved in the Spring Batch

@PostConstruct by JSR-250, executed after executing the constructor, equivalent to the xml configuration file in the bean initMethod

@PreDestory by JSR-250, before performing the destruction Bean, equivalent to the bean xml configuration file destroyMethod

 

4. . 6 , @Value annotations

@Value injection attribute value (the property)

Support of the injection follows:

// inject ordinary strings

@Value("Michael Jackson")

String name;

 

// inject operating system properties

@Value("#{systemProperties['os.name']}")

String osName;

 

// inject expression result

@Value("#{ T(java.lang.Math).random() * 100 }")

String rNum;

 

// inject other bean properties

@Value("#{domClass.name}")

String name;

 

// inject file resources

@Value("classpath:com/hgs/hello/test.txt")

Resource file

 

// injection site resources

@Value("http://www.baidu.com")

Resource url;

 

// injection configuration file

@Value("${bo.name}")

String boName

Injection configuration using the method:

① write a configuration file (test.properties)

book.name = alive

 @PropertySource loading a configuration file (the class)

@PropertySource("classpath/com/xxx/test.properties")

 Need to configure a PropertySourcesPlaceholderConfigurer of bean.

 

4. . 7 , context switching

@Profile to set the current configuration environment context to use by setting Environment of ActiveProfiles. (Classes or methods)

@Conditional Spring4 can be used in this condition, then the annotation defines bean, by implementing the Condition interface and override matches method, to determine whether the bean is instantiated. (Methods)

 

4. . 8 , asynchronous relevant

@EnableAsync configuration class, this comment by open support for asynchronous tasks (upper class) narrative AsyncConfigurer Interface

@Async use the annotation bean method to declare its actual implementation is an asynchronous task (all the way on the method or the class will be asynchronous, asynchronous tasks require @EnableAsync open)

 

4. . 9 , the timing of tasks related to

@EnableScheduling class configuration on the use of open support for scheduled tasks (like on)

@Scheduled to declare this is a task, including cron, fixDelay, fixRate other types (the method, you must first open the Scheduled Tasks Support)

 

4. 10 , @ the Enable * explanatory notes

These annotations primarily to enable support for the xxx.

@EnableAspectJAutoProxy turn on automatic proxy support for AspectJ

@EnableAsync open support asynchronous method

@EnableScheduling open Scheduled Tasks support

@EnableWebMvc open configuration support of Web MVC

@EnableConfigurationProperties turn supports the configuration of @ConfigurationProperties Bean notes

@EnableJpaRepositories open support for the SpringData JPA Repository

@EnableTransactionManagement open transaction annotation support

@EnableTransactionManagement open transaction annotation support

@EnableCaching open an annotation-caching support

 

4. 11 , test-related notes

@RunWith runner, Spring is usually used to support for the JUnit

@RunWith(SpringJunit4ClassRunner.class)

@ContextConfiguration used to load configuration ApplicationContext, wherein the attribute is used to load the configuration classes Class

@ContextConfiguration(classes={TestCofig.class})

 

5 , SpringMVC comments

In the open configuration @EnableWebMvc class configuration supports the Web MVC, as some ViewResolver MessageConverter or the like, without sentence, WebMvcConfigurerAdapter override method (for the configuration SpringMVC).

@Controller class is declared in the Controller SpringMVC

@RequestMapping Web requests for mapping, comprising (a class or method) and the access path parameters

@ResponseBody support the return value placed in the response, rather than a page, usually the user returns json data (return value near or method)

@RequestBody allowed request parameters in the request body, rather than directly connected after the address. (On the front of the parameter)

@PathVariable parameters for the receive path, such @RequestMapping ( "/ hello / {name}") path before stated, the annotation on the parameters, to obtain the value, as is generally the interface method Restful.

@RestController The annotation is a combination of notes, equivalent to a combination of @Controller and @ResponseBody, and notes on the class, which means all of the methods of the Controller will assume added @ResponseBody.

@ControllerAdvice by the annotation, we can place the profile for the global controller in the same position, the annotation @Controller method, can be utilized @ ExceptionHandler, @ InitBinder, @ ModelAttribute annotation to the method, which all annotated! the method in the controller RequestMapping effective.

@ExceptionHandler used for global exception handling in the controller

@InitBinder to set WebDataBinder, WebDataBinder reception request parameters used to automatically bind the Model.

Originally role @ModelAttribute is to bind key-value pairs in the Model, is to let the global @RequestMapping have access to the key set here in @ControllerAdvice in.

@Required suitable for bean property setter methods, and that the affected bean properties must be populated when configured in the XML configuration file. Otherwise, the container will throw a BeanInitializationException exception.

Under @SessionAttributes default Spring MVC data storage model to request domain. When the end of a request, the data on the failure. If you want to use across the page. We need to use the session. And @SessionAttributes annotation can store such data into a model of the domain session

parameter:

  • names: This is an array of strings. Which should be written in the name of the session data needs to be stored to.
  • types: the type specified parameters, the corresponding type of model parameters stored in the session
  • value: and the names are the same.

Sample code :

@Controller
@SessionAttributes(value={"names"},types={Integer.class})
public class ScopeService {
       @RequestMapping("/testSession")
       public String test(Map<String,Object> map){
           map.put("names", Arrays.asList("a","b","c"));
           map.put("age", 12);
           return "hello";
       }
}

 

Notes common detailed explanation:

@Controller

SpringMVC, the distribution of Controller responsible for processing requests from the DispatcherServlet, it requests the user service data after a treatment layer. Package Model, the Model and then returned for display to the corresponding View. In SpringMVC provided in a very simple way to define the Controller, you do not need to inherit a particular class or implement a specific interface, just use @Controller mark a class is Controller, and then use some annotations to define @RequestMapping and @RequestParam etc. URL mapping between the request and the Controller method, this Controller can be accessible to the outside world. 

 

@Service

Service level component for labeling business layer component to indicate the definition of a bean (entity classes), automatic write according to a first instance of the bean class name in lowercase letters bean, for example, Chinese instantiated as a chinese, if you need to change the name himself : @Service ( "you change the bean name").

  

@Repository

It is used for the data access layer class (DAO layer) is identified as a Spring Bean. The only specific annotations can be marked on the DAO classes.

Why @Repository DAO class can only be marked on it? This is because not only the effect of the annotation as a class identification Bean, it can simultaneously marked class data access exceptions thrown exception type of encapsulation Spring access data. Spring itself provides a rich and is independent of the access technology specific data structure data access exceptions, for different packages persistence framework thrown exception, such that the frame independent of the underlying abnormality.

 

@RequestMapping

RequestMapping is a process for annotation request address mapping, it can be used for class or method. For the class, all the methods in response to the request class are represented in the address as the parent path.

 

@Autowired

@Autowired annotation, it can be labeled class fields, methods and constructors, the automatic assembly work is completed.

 

@ResponseBody

@ResponseBody annotation object after the action of the controller method returns to the specified format converted by a suitable converter (actually the effect @ResponseBody java object into json data format.), Is written to the response object body area, often used to return JSON data or XML data, need to pay attention to it, after trying to use this annotation processor would not go, but directly to write data to the input stream, the same effect as by his response output data format specified objects.

 

@MapperScan

Action: Specifies where the package into an interface implementation class, then all packets are generated corresponding to the following interface implementation class after compilation

Add Location: Springboot start in the top category added.

 

@SpringBootApplication

Start class notes (usually in the root under):

This note was modified @ Configuration, @ EnableAutoConfiguration, @ ComponentScan three notes

1, @ SpringBootConfiguration inherited from @Configuration, consistent both functions are denoted by the current class is the class configuration, and will declare the current class to the one or more annotated example of a method @Bean labeled container into the spring, and instance name is the method name.

2, @ EnableAutoConfiguration: is the core function spring boot, and automatic configuration. This comment tells SpringBoot "guess" how would you want to configure Spring, based on what you've added jar dependencies. If the spring-boot-starter-web has been added Tomcat and Spring MVC, this comment will automatically assume you are developing a web application and add the appropriate spring set.

@EnableAutoConfiguration generally recommended configuration in the root package, so that all the sub-packages, classes can be checked to find.

3、@ComponentScan

Popular speaking, @ ComponentScan notes will automatically scan all designated under the package marked with @Component annotated classes, and registered as bean, of course, including @Component under sub-notes @ Service, @ Repository, @ Controller. @ComponentScan comment is no similar property.

 

@requestParam

@requestParam master to be used for Sprin gMVC acquisition parameters background control layer, a similar one is request.getParameter ( "name"), which has three common parameters: defaultValue = "0", required = false, value = "isApp"; defaultValue represents the set default values, required by boolean setting is what must be passed in parameter, value value indicates acceptance of an incoming parameter type.

 

@Scope

To configure the spring bean scope that identifies the scope of the bean.

The default value is a singleton

  • singleton: single embodiment mode, there is only one global instance
  • prototype: prototype model, every acquisition Bean when there will be a new instance
  • request: request indicates that while the bean is only valid in the current HTTP request for each HTTP request will generate a new bean,
  • session: session indicates that the scope of the bean is only valid while the current HTTP session for each HTTP request will generate a new bean,
  • global session: is only useful in portal applications, to each create a new global http session Bean instance.

 

@RestController

After Spring4 added annotation, the original return @Controller @ResponseBody json need to cope with, if direct @RestController Alternatively @Controller not necessary to configure @ResponseBody, default return json format.

Sample code:

@RestController
public class TestController {
        @RequestMapping("/test")
        public String test(Map<String,Object> map){
            return "hello";
        }
}

 

1@Autowired @Qualifier @Resource

Usage: marked on the member variable, or the set method. @Resource @Autowired and are intended for the automatic assembly bean. (To be exact @Resource is jdk own notes);

Difference: @Autowired assembly by default is to find the type, name lookup can also be specified by @Qualifier. The @Resource default lookup by name, of course, you can also specify the type, specify the name or specify. If you can not find the specified type of time or find more will throw an exception. Specify the type and name of the time, you will find unique match of bean, if more found thrown.

Example:

/*
*接口
*/
public interface PersonService{
    public void eat();
    public void play();
}
/*
*接口实现类
*/
@Service("personService")
public class PersonServiceImpl implements PersonService{
    @Override
    public void eat(){  
         System.out.println("eat");
    }
    @Override
    public void play(){
        System.out.println("play");
    }
}
/*
*调用类
*/
public class Demo{
    @Resource
    private PersonService personService;
    @Autowired
    private PersonService personService2;
    
    @Autowired
    @Qualifier("personService")
    private PersonService personService3;
    
    public void test(){
        personService.eat();
        personService2.eat();
    }
}

 

2@Service @Component @Controller @Repository

Usage: are marked on the class name used to register a Spring bean into context.

Difference: @Service for the service layer; the layer for controlling @Controller; @Repository for DAO layer; uncertainty with @Component

Example: see sample code (Usage of the same Service)

 

3@RequestMapping @RequestParam

Usage: @RequestMapping marked on a control layer above category mapping request path; @RequestParam a request parameter maps;

Example:

/*
*控制层类
*/
@Controller
@RequestMapping("/register")
public class RegisterUser{
    public void register(@RequestParam("ownerId") int ownerId){
        //dosomething
    }
}

Original link: https://www.cnblogs.com/benming/p/11583545.html

Published 54 original articles · won praise 47 · views 10000 +

Guess you like

Origin blog.csdn.net/cy973071263/article/details/104572972