Objective
This essay will make a simple filing of the common annotations in Spring boot, and the order of writing will start from the start-up class and be extended to both inside and outside, for the purpose of sharing and for the convenience of future review and inspection.
1. Application
The Startup class example is as follows:
@SpringBootApplicationpublicclass Application { publicstaticvoidmain(String[] args) { SpringApplication.run(Application.class, args); }}
The first note to be explained is: @SpringBootApplication, from an intuitive perspective, he is a prerequisite for springapplication to enter a complex set of start-up processes. Enter the source code we can observe that this is a combination of annotations, its facets are also three annotations, respectively: @SpringBootConfiguration, @EnableAutoConfiguration, @ComponentScan.
What really works in @SpringBootConfiguration is @Configuration, that is, labeling the current class as a Javaconfig configuration class (here, any class labeled @Configuration is a configuration class, any labeled @ The Bean's method whose return value is the definition of a bean).
@EnableAutoConfiguration is the core of the appeal composition annotation, which can be obtained from the name: Automatic configuration is enabled, and he uses @Import to inject all eligible @Configuration configurations into the IoC container, as defined below:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Inherited@AutoConfigurationPackage@Import(AutoConfigurationImportSelector.class)public@interface EnableAutoConfiguration { "spring.boot.enableautoconfiguration"; excludedefault {}; excludeNamedefault {};}
@ComponentScan as the name implies, he scans components with specific callouts (such as @Controller, @Component, @Service, @Repository) and injects them into the IoC container.
2. Test
The test class example is as follows:
@RunWith(SpringRunner.class)@SpringBootTestpublicclass ApplicationTests { @Test publicvoidcontextLoads() { }}
@RunWith (Springrunner.class) is to run the test using the Spring IoC container, @SpringBootTest Create the springapplication context, and @Test label the test method. It is recommended to read the "Springboot Unit Test", written in detail, I will not go into the details, to be empty to complement a few complex test case analysis.
3. Basic Annotations 3.1 @Service & @Repository
They are the key to interface-oriented programming that is easily implemented in Spring Boot, one for the logic layer and one for the data layer, as shown in the following example:
publicinterface HelloService { notSay();}
@Servicepublicclassimplements HelloService { @Override publicnotSay() { return"shut up"; }}
Personally, this is a very graphic representation of the "Convention better than configuration", which can be understood as Spring Boot, which generates a Bean by default:
<bean id="HelloService"class="com.youclk.annotation.service.impl.HelloServiceImpl"></bean>
3.2 @Component
Callout components can function at any level.
3.3 @Controller
The controller example is as follows:
@RestController Public classHellocontroller {Private FinalHelloService HelloService;@Autowired Public Hellocontroller(HelloService HelloService) { This.HelloService= HelloService; }@GetMapping("/{id}") PublicStringsay(@PathVariable("id") Integer ID,@RequestParam("Name") (String name) {return(String. Format("Id=%d, Name=%s;p Lease%s", ID, name, HelloService.Notsay())); }}
@RestController look at the source code to see its combination of @Controller + @ResponseBody annotations:
@Target(ElementType.TYPE)@Retention(RetentionPolicy.RUNTIME)@Documented@Controller@ResponseBodypublic@interface RestController { @AliasFor(annotation = Controller.class) valuedefault"";}
@GetMapping is actually a further encapsulation of the @RequestMapping (method = Requestmethod.get), as well as Post, Delete, Put, and so on, different types of requests have their corresponding encapsulation, can play a lot less code.
Others are also at a glance in the example: @Autowired auto-transfer, @PathVariable to take a value from the URL, @RequestParam to take a value from the parameter.
4. Exception Handling
Examples are as follows:
@ControllerAdvicepublicclass GlobalException { @ResponseBody @ExceptionHandler publicprocessException(Exception e) { return"error: " + e.getMessage(); }}
There's nothing to say, @ExceptionHandler can filter specific exception types:@ExceptionHandler(Exception.class)
5. Configuration
By @Value you can get directly to the properties in the configuration file, but the meaning is not very large, for example:
@Value("${my.name}") private
More time should go to get an object, example:
@Component @ Configurationproperties (prefix = "my" ) public class My {private String name; private Integer age; public String getname () {return name; } public void setname (String name) {
this .
name = name; }
public Integer
getage () {
return age; }
public
void
setage (Integer age) { span class= "kw" >this .
age = age; }}
@Profiles activated by environment variables, I think it's not a very good solution, not much used, example:
@profile("dev"@profile("prod"
Spring Boot advocates an agreement over configuration, but sometimes we don't want to be compliant, as follows:
@Configuration Public classdbconfiguration {Private FinalDB DB;@Autowired Public dbconfiguration(DB db) { This.DB= DB; }@Bean(name ="DataSource") PublicDataSourceDataSource() {Basicdatasource DataSource =New Basicdatasource(); DataSource.Setdriverclassname(Db.Driverclassname); DataSource.SetUrl(Db.Driverurl); DataSource.Setusername(Db.Driverusername); DataSource.SetPassword(Db.Driverpassword);returnDataSource; }@Bean PublicPlatformtransactionmanagerTransactionManager() {return New Datasourcetransactionmanager(DataSource()); } }
6. Other
The @Qualifier is to resolve conflicts for multiple implementations of an interface, but this is generally avoided in design, so it is not very common, for example:
@Service("service1")publicclassimplements HelloService {}@Service("service2")publicclassimplements HelloService {}
@Autowired@Qualifier("service1")HelloService helloService;
@Resource (name= "name", type= "type") is similar to @Autowired and is not commonly used.
Conclusion
Recently is looking for new job opportunities, if there is intention, welcome message,: YOUCLK.
Java-spring Boot Annotations