1. Startup related

@SpringBootApplication

Contains ==@ComponentScan==, ==@Configuration==, and == @enableAutoConfiguration == annotations.

@ComponentScan

Where @ComponentScan lets Spring Boot scan beans annotated by @Component (@Service,@Controller) into the Configuration class and add it to the application context.

@Configuration (detailed version below)

@Configuration is equivalent to spring’s XML Configuration file; Allow registering additional beans or importing additional configuration classes in the Spring context.

@EnableAutoConfiguration

@enableAutoConfiguration Enables the automatic configuration mechanism of SpringBoot.

2. The Spring Bean

@Autowired

Automatically import objects into classes. The injected classes are also managed by the Spring container. For example, the Service class is injected into the Controller class.

@Slf4j
@Service
public class ProjectServiceImpl  implements ProjectService {
}

@Autowired
private ProjectService projectService;
@PostMapping ("/application")
public ResultVo findProject(@RequestBody @Validated FindProjectRequest request) {
    return projectService.findProject(request);
}
Copy the code

@Resource

public class Hello {

    @Resource(name = "HappyClient")
    private HappyClient happyClient;
    
    @Resource(type = HappyPlayAno .class)
    private HappyPlayAno happyPlayAno;
}
Copy the code

@Resource acts like @autoWired and can be tagged on setter methods of fields or properties.

This place notice the difference here

  • A: Provider @autoWired is a Spring annotation, @resource is a Javax. annotation annotation, but from JSR-250, J2EE provided, requires JDK1.6 or above.
  • B: Injection mode @autoWired only inject according to Type; @resource is automatically injected by Name by default, but also by Type.
  • C: attribute

The @AutoWired annotation can be used to annotate attributes, constructors, and methods of a class. By default, the object it depends on must exist (the bean is available), and if you want to change the default, you can set its required property to false. Another important point is that the @autoWired annotation is assembled by type by default. If the container contains more than one Bean of the same type, an exception will not be found when the container is started. The solution is to qualify it with the ** @qualifier ** annotation specifying the name of the Bean to be injected. The @resource has two important attributes: name and type. The name attribute specifies byName. If the name attribute is not specified, when the annotation is on the field, the default is to take the field name as the bean name to find the dependent object, and when the annotation is on the setter method of the property, the default is to take the property name as the bean name to find the dependent object. Note that the @resource annotation falls back to type assembly if the name attribute is not specified and the dependent object is still not found by default name. But once you specify the name attribute, you can only assemble by name.

  • D: @resource annotation is more flexible, can specify the name, can specify the type; The @AutoWired annotation may throw exceptions when it is assembled, especially if there are multiple bean types. The solution is to add @qualifier to qualify it.

@RestController

The @RestController annotation is a combination of ==@Controller== and == @responseBody ==, indicating that this is a Controller bean and that the return value of the function is inserted directly into the BODY of the HTTP response, which is a REST style Controller.

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Controller
@ResponseBody
public @interface RestController {
    String value() default "";
}
Copy the code

@Repositor

Annotate a DAO component class.

@Service

Annotate a business logic component class.

@Controller

@Controller: Defines the Controller class that in spring projects is responsible for forwarding URL requests from users to the corresponding service interface (service layer). Normally this annotation is in a class and usually the method needs to be used with the @requestMapping annotation.

@ResponseBody

@Controller
@RequestMapping("/test")
@Slf4j
public class TestController {

    @RequestMapping("/hello.json")
    @ResponseBody
    public JsonData hello() {
        log.info("hello");
        return JsonData.success("hello, permission");
    }
Copy the code

What it does: Writes the return value of the method, ==, in a specific format to the body area of response, and returns the data to the client ==.

When the ResponseBody is not written above the method, the bottom layer encapsulates the method’s return value as a ModelAndView object. After using this annotation, you don’t go through the processor, but write the data directly to the input stream, which has the same effect as writing the data in the specified format through the Response object.

  • If the return value is a string, the string is written directly to the client;
  • If it is an object, the object is converted to a JSON string and then written to the client.

If an object is returned, it is encoded utF-8. If the value is returned as String, the default encoding is ISO8859-1. Garbled characters may appear on the page. So in annotations we can change the encoding format manually, for example

@RequestMapping(value="/cat/query",produces="text/html; Charset = utf-8 "),Copy the code

The path of the request is preceded by the encoding format.

The principle of

How is the return value of a control-layer method converted to a JSON-formatted string? It is implemented through methods in HttpMessageConverter, which is an interface that is transformed in its implementation class.

  • In the case of a bean object, the object’s getXXX () method is called to get the property value and encapsulate it in key-value pairs, which are then converted into JSON strings.
  • If it is a map set, use get(key) to obtain the value and encapsulate the value.

@Component, @repository, @Service, and @Controller are essentially the same class of annotations, with the same usage and functionality. The difference lies in the type of Component identified.

@Component can replace @repository, @service, and @Controller because they are annotated by @Component. The following code

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
    String value() default "";
}
Copy the code

Reference herein great god article blog.csdn.net/jiahao1186/…

@Scope

Declare the scope of the Spring Bean using:

@Bean
@Scope("singleton")
public Person personSingleton() {
    return new Person();
}
Copy the code

There are four common Spring Bean scopes:

  • Singleton: A unique bean instance. Beans in Spring are singleton by default.
  • Prototype: Each request creates a new bean instance.
  • Request: Each HTTP request generates a new bean that is valid only within the current HTTP Request.
  • Session: Each HTTP request generates a new bean that is valid only for the current HTTP session.

@Configuration

You can use the @Component annotation instead, but using the Configuration annotation to declare Configuration classes is more semantic.

Use @Configuration to define Configuration classes, == to replace XML Configuration files ==, annotated classes that contain one or more methods annotated by @Bean, These methods will be AnnotationConfigApplicationContext or AnnotationConfigWebApplicationContext scanned, and used to construct the bean definition, initialize the Spring container.

@Configuration public class AppConfig { @Bean public MyService myService() { return new MyServiceImpl(); }}Copy the code

This is very similar to what happens in Spring’s XML file

<beans> 
	<bean id="myService" class="com.acme.services.MyServiceImpl"/> 
</beans>
Copy the code

Note: The @Configuration annotation Configuration class has the following requirements:

  • 1.@Configuration cannot be final;
  • 2.@Configuration cannot be an anonymous class;
  • 3. The nested Configuration must be a static class.

@ the use of the Configuration can see this great god article www.cnblogs.com/duanxz/p/74…

@Component

@Configuration public static class Config { @Bean public SimpleBean simpleBean() { return new SimpleBean(); } @Bean public SimpleBeanConsumer simpleBeanConsumer() { return new SimpleBeanConsumer(simpleBean()); }}Copy the code
@Component public static class Config { @Bean public SimpleBean simpleBean() { return new SimpleBean(); } @Bean public SimpleBeanConsumer simpleBeanConsumer() { return new SimpleBeanConsumer(simpleBean()); }}Copy the code
  • The first code works, and as expected, the SimpleBeanConsumer will get a link to a singleton SimpleBean.
  • The second configuration is completely wrong, because Spring will create a singleton of SimpleBean, but SimpleBeanConsumer will get another instance of SimpleBean(that is, calling new SimpleBean() directly, This bean is not spring-managed), since the new SimpleBean() instance is outside the Spring context control.

Principle resolution Using @Configuration, all methods labeled @Bean are wrapped into a CGLIB wrapper that works as if it were the first call to the method, so the body of the original method is executed and the final object is registered in the Spring context. All further calls return only beans retrieved from the context.

In the second block above, the new SimpleBeanConsumer(simpleBean()) calls only a pure Java method. To correct the second code block, we can do this

@Component public static class Config { @Autowired SimpleBean simpleBean; @Bean public SimpleBean simpleBean() { return new SimpleBean(); } @Bean public SimpleBeanConsumer simpleBeanConsumer() { return new SimpleBeanConsumer(simpleBean); }}Copy the code

The great spirit link: blog.csdn.net/u010648555/…

3. Handle common HTTP request types

@RequestMapping

@requestMapping: @requestMapping (/path) indicates that the controller processes all UR L requests of /path. RequestMapping is an annotation to handle request address mapping, which can be used on a class or method. Used on a class, this address is used as the parent path for all methods in the class that respond to requests. This annotation has six attributes:

params

Specifies that the request must contain some parameter values of yes for this method to process.

headers

Specifies that the request must contain some specified header value for the method to process the request.

@RequestMapping (value= "testHeaders" , headers={ "host=localhost" , "Accept" })
    public String testHeaders() {
       return "headers" ;
    } 
Copy the code

The usage and functionality of the HEADERS attribute are similar to that of the Params attribute. In the above code, the testHeaders method can only be accessed when the request header contains Accept and the host is localhost.

  • Value: Specifies the actual address of the request, which can be the URI Template pattern
@RequestMapping(value = "bkpic.page", method = RequestMethod.POST)
@ResponseBody
public JsonData upload(@RequestParam(value = "picture", required = false) MultipartFile picture, HttpServletRequest request) {
}

Copy the code

consumes

  • Designated processing requests submitted Content Type (the content-type), such as application/json, text/HTML.

produces

  • Specifies the type of content to return, only if the specified type is included in the Request header (Accept)

@RequestParam

@RequestMapping("/changeUsers.json")
@ResponseBody
public JsonData changeUsers(@RequestParam("roleId") int roleId, @RequestParam(value = "userIds", required = false, defaultValue = "") String userIds) {
    List<Integer> userIdList = StringUtil.splitToListInt(userIds);
    sysRoleUserService.changeRoleUsers(roleId, userIdList);
    return JsonData.success();
}
Copy the code

@pathvariable: PathVariable. Such as

@RequestMapping(method = RequestMethod.GET)
public List<AccessDTO> searchAccess(@RequestParam(required = false) String service,
                                    @RequestParam(required = false) String application,
                                    @PathVariable String env) {
                                    }
Copy the code

method

Specify the method type of the request, GET, POST, PUT, DELETE, and so on

  • GET: Requests to GET a specific resource from the server. For example: GET /users (GET all students)
@getMapping ("users") = @requestMapping (value="/users",method= requestmethod.get) @getMapping ("/users") public ResponseEntity<List<User>> getAllUsers() { return userRepository.findAll(); }Copy the code
  • POST: Creates a new resource on the server. For example: POST /users (create students)
@postmapping ("users") = @requestMapping (value="/users",method= requestmethod. POST) @postmapping ("/users")public ResponseEntity<User> createUser(@Valid @RequestBody UserCreateRequest userCreateRequest) { return userRespository.save(user); }Copy the code
  • PUT: Updates the resource on the server (the client provides the updated entire resource). For example: PUT /users/12 (update student number 12)
@putMapping ("/users/{userId}") = @requestMapping (value="/users/{userId}",method= requestmethod.put) @PutMapping("/users/{userId}")public ResponseEntity<User> updateUser(@PathVariable(value = "userId") Long userId, @Valid @RequestBody UserUpdateRequest userUpdateRequest) { ...... }Copy the code
  • DELETE: Deletes a specific resource from the server. For example: DELETE /users/12 (DELETE student number 12)
@deletemapping ("/users/{userId}") = @requestMapping (value="/users/{userId}",method= requestmethod.delete) @DeleteMapping("/users/{userId}")public ResponseEntity deleteUser(@PathVariable(value = "userId") Long userId){ ...... }Copy the code
  • PATCH: Updates resources on the server (the client provides the changed properties, which can be regarded as partial updates). It is rarely used, so there are no examples here.
In general, in actual projects, PATCH request is used to update data after PUT is insufficient. @PatchMapping("/profile") public ResponseEntity updateStudent(@RequestBody StudentUpdateRequest studentUpdateRequest) { studentRepository.updateDetail(studentUpdateRequest); return ResponseEntity.ok().build(); }Copy the code

4. Read the configuration information

The data source application. Yml

Wuhan2020: come on wuhan in 2020! Come on China! Books: - name: 1 description: 11-name: 2 description: 22 - name: 3 description: 33Copy the code

@ value (common)

Use @value (“${property}”) to read simpler configuration information:

@Value("${wuhan2020}")
String wuhan2020;
Copy the code

@ConfigurationProperties

@Component @ConfigurationProperties(prefix = "library") class LibraryProperties { @NotEmpty private String location; private List<Book> books; @Setter @Getter @ToString static class Book { String name; String description; } omit getter/setter...... }Copy the code

The configuration information is read and bound to the bean via @ConfigurationProperties.

@PropertySource

PropertySource Reads the specified properties file

@Component @PropertySource("classpath:website.properties") class WebSite { @Value("${url}") private String url; Omit the getter/setter... }Copy the code

Draw lessons from the great spirit here segmentfault.com/a/119000002…

5. Verify parameters

JSR(Java Specification Requests) is a set of Java Specification Requests (JSR) standards for validation of JavaBean parameters. It defines a number of commonly used validation annotations that can be added directly to the properties of javabeans so that validation can be performed when needed. Very convenient!

Some common annotations for field validation

@notempty the annotated string cannot be null and it cannot be null. @notBlank the annotated string is not null, And it must contain a non-whitespace character @Null the annotated element must be Null @NotNull the annotated element must not be Null @AssertTrue the annotated element must be true @AssertFalse The annotated element must be false @pattern (regex=,flag=) The annotated elements must conform to the specified regular expression. @email The annotated elements must be in the Email format. @min (value) The annotated element must be a number and its value must be greater than or equal to the specified minimum @max (value) The annotated element must be a number and its value must be less than or equal to the specified maximum @decimalmin (value) The annotated element must be a number, Its value must be greater than or equal to the specified minimum @decimalmax (value) The annotated element must be a number, The value must be less than or equal to the specified maximum @size (Max =, min=) The Size of the annotated element must be within the specified range @digits (integer, fraction) The annotated element must be a number, The value must be within an acceptable range. @past the annotated element must be a Past date. @future the annotated element must be a Future date......Copy the code

The sample

@data @allargsconstructor @noargsconstructor public class Person {@notnull (message = "classId cannot be null ") private String classId; @size (Max = 33) @notnull (message = "name cannot be empty ") private String name; @Pattern(regexp = "((^Man$|^Woman$|^UGM$))", Message = "sex ") @notnull (message = "sex ") private String sex; @email (message = "Email format is incorrect ") @notnull (message =" Email cannot be empty ") private String Email; }Copy the code

We add the @valid annotation to the argument we need to validate, which will be thrown if the validation fails

MethodArgumentNotValidException. @RestController @RequestMapping("/api") public class PersonController { @PostMapping("/person") public ResponseEntity<Person> getPerson(@RequestBody @Valid Person person) { return ResponseEntity.ok().body(person); }}Copy the code

Be sure to annotate the class with the Validated parameter, which tells Spring to validate method parameters.

@RestController @RequestMapping("/api") @Validated public class PersonController { @GetMapping("/person/{id}") public ResponseEntity<Integer> getPersonByID(@valid@pathVariable ("id") @max (value = 5,message = "out of id") Integer id) {ResponseEntity<Integer> getPersonByID(@valid@pathvariable ("id") @max (value = 5,message =" out of id") Integer id) { return ResponseEntity.ok().body(id); }}Copy the code

6.@Transactional

Use the @Transactional annotation on the method you want to start the transaction!

@Transactional(rollbackFor = Exception.class)
public void save() {
  ......
}
Copy the code

We know that exceptions are divided into run-time exceptions and non-run-time exceptions. If the @Transactional annotation is not configured with the rollbackFor attribute,== the transaction will rollback only when it encounters a RuntimeException. With rollbackFor= exception.class, the transaction will rollback when it encounters a non-runtime Exception = =.

The @Transactional annotation is usually used to implement classes or methods.

  • Applied to classes: When the @Transactional annotation is placed ona class, all public methods of that class are configured with the same transaction attribute information.
  • Applied to methods: When a class is configured with @Transactional and a method is configured with @Transactional, the method’s transaction overrides the Transactional configuration information of the class.

The sample

@Service public class CompanyServiceImpl implements CompanyService { @Autowired private CompanyDAO companyDAO; @Transactional(propagation = Propagation.REQUIRED, readOnly = false, rollbackFor = Exception.class) public int deleteByName(String name) { int result = companyDAO.deleteByName(name); return result; }... }Copy the code

To be continued… Welcome to leave a message…

@ Inherited blog.csdn.net/ab411919134… @ ConditionalOnClass blog.csdn.net/lbh199466/a…

@ Target blog.csdn.net/qq_30347133…

@ Retention blog.csdn.net/b_just/arti…

@ SuppressWarnings blog.csdn.net/u012994320/… @ Aspect blog.csdn.net/zhengchao19…

Blog.csdn.net/fz137688842… @Slf4j

@EnableWebMvc

@Primary

@EnableSwagger2

@EnableAsync

@Authority(needLogin = true)

@ResponseStatus(HttpStatus.CREATED)

@pmskey (code = “application”, title = “list of applications “)

@SerializedName(“biz_id”)

@ControllerAdvice(annotations = ResponseBody.class)

@ExceptionHandler(value = Exception.class)

@Order(0)

@Around(“execution(* org.apache.dubbo.admin.controller.. (..) )”

@SPI(“zookeeper”)

@EnableTransactionManagement

@MapperScan(basePackages = “org.apache.dubbo.admin.dao.mapper”)

@ComponentScan(basePackageClasses = {org.apache.dubbo.admin.DubboAdminApplication.class, PermitContextManager.class})

This public account to share their own from programmer xiao Bai to experience spring recruitment autumn recruitment cut more than 10 offer interview written test experience, including [Java], [operating system], [computer network], [design mode], [data structure and algorithm], [Dacheng face by], [database] look forward to you join!!

1. Computer network —- Three times handshake four times Wave 2. Dream come true —– Project self-introduction 3. Here is the design pattern you asked for. 4. Close to 30 interviews shared