1,@Autowired
@Autowired(required=true): indicates that the object must be successfully injected during automatic injection, otherwise an error is reported. Default is true@Autowired(required=false): it means that the object is not a required object during automatic injection. If there is, it will be injected. If there is no error, it will not be reported
2. Customize the json data of the error page
If there is no adaptive effect, it should be forwarded to / error for adaptive response effect processing
3,@Conditional
@Conditional is a new annotation provided by spring 4. It is used to judge according to certain conditions and register the bean in the container only when the conditions are met
4. @ Import (focus on the use of two Import interfaces)
@The Import parameter value receives a Class array and adds the Class you passed in to the IOC container with the full Class name as the id
1),ImportSelector
ImportSelector emphasizes reusability. To use it, you need to create a class to implement the ImportSelector interface. The return value of the implementation method is a string array, that is, the full class name of the component to be injected into the container. id is also the full class name.
//Custom logic returns the components to be imported public class MyImportSelector implements ImportSelector { // The return value is the full class name of the component imported into the container // AnnotationMetadata: all annotation information of the class currently annotated with @ Import annotation public String[] selectImports(AnnotationMetadata importingClassMetadata) { return new String[] { "test.spring.ZhangSan", "test.spring.LiSi", "test.spring.WangWu" }; } }
2),ImportBeanDefinitionRegistrar
spring officially implements the dynamic injection mechanism of @ Component, @ @ Service and other annotations in this way. Define an implementation class of ImportBeanDefinitionRegistrar, and then use @ Import import on the Configuration class with @ Configuration annotation
Specific usage: create an implementation class of ImportBeanDefinitionRegistrar, implement the registerBeanDefinitions method, and inject components.
public class MyBeanDefinitionRegistrar implements ImportBeanDefinitionRegistrar { /** * @param annotationMetadata All annotation information of the class currently annotated with @ Import annotation * @param beanDefinitionRegistry BeanDefinition Registration class for */ public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) { RootBeanDefinition beanDefinition = new RootBeanDefinition(Cat.class); beanDefinitionRegistry.registerBeanDefinition("cat",beanDefinition); } } //give the result as follows @Configuration @Import(value = {MyBeanDefinitionRegistrar.class}) public class MyConfig { } /**test result beanName: org.springframework.context.annotation.internalConfigurationAnnotationProcessor beanName: org.springframework.context.annotation.internalAutowiredAnnotationProcessor beanName: org.springframework.context.annotation.internalCommonAnnotationProcessor beanName: org.springframework.context.event.internalEventListenerProcessor beanName: org.springframework.context.event.internalEventListenerFactory beanName: myConfig beanName: cat */
5,@Options
The @ Insert annotation is used in MyBatis mapper to Insert data information, but the self incrementing primary key is not returned. If you need to return the auto increment primary key, you need to add the @ Options annotation after @ Insert
@Options(userGeneratedKeys = true, keyProperty = "id") @Insert("insert into department(departmentName) values(#{departmentName})") public int insertDept(Department department);
6. Java callback mechanism
Callback: that is to call a method C in class B in class A, and then call D in class A in B class, D is called callback method.
There are always certain interfaces between software modules. In terms of calling methods, they can be divided into three categories: synchronous call, callback and asynchronous call.
Callback is a special call. The three methods are also different:
- Synchronous callback: blocking, one-way.
- Callback: bidirectional (similar to the two gears of a bicycle).
- Asynchronous callback: notification through asynchronous message.
7,@RequestParam
@RequestParam is to create a mapping relationship between the request parameters and the formal parameters of the controller method
@The RequestParam annotation has three attributes:
value: Specifies the parameter name of the request parameter assigned to the formal parameter
required: sets whether this request parameter must be transmitted. The default value is true
If it is set to true, the current request must transmit the request parameter specified by value. If the request parameter is not transmitted and the defaultValue property is not set, the page will report an error 400: Required String parameter 'xxx' is not present; If it is set to false, the current request does not have to transmit the request parameter specified by value. If there is no transmission, the value of the formal parameter identified by the annotation is null
defaultValue: whether the required property value is true or false, when the request parameter specified by value is not transmitted or the transmitted value is' ', the default value will be used to assign value to the formal parameter.
@Autowired is marked on the method. When the Spring container creates the current object, it will call the method to complete the assignment; Method, and the value of the custom type is obtained from the ioc container. (similar to setter method, what type of parameter is automatically injected into the attribute assignment in the object)
8,@EnableConfigurationProperties
@The function of the EnableConfigurationProperties annotation is to make the class using the @ ConfigurationProperties annotation effective.
explain:
- If a configuration class only configures the @ ConfigurationProperties annotation and does not use @ Component, then the bean s transformed from the properties configuration file cannot be obtained in the IOC container. To put it bluntly, @ EnableConfigurationProperties is equivalent to an injection of the class using @ ConfigurationProperties.
- The test found that @ ConfigurationProperties and @ EnableConfigurationProperties are particularly related
Test certificate:
@Relationship between ConfigurationProperties and @ EnableConfigurationProperties
@The EnableConfigurationProperties document explains that when the @ EnableConfigurationProperties annotation is applied to your @ Configuration class, any beans annotated by @ ConfigurationProperties will be automatically configured by the Environment property. This style of Configuration is particularly suitable for use with the external YAML Configuration of spring application.
Test findings:
- Register with @ EnableConfigurationProperties
@ConfigurationProperties(prefix = "service.properties") public class HelloServiceProperties{ private static final String SERVICE_NAME = "test-service"; private String msg = SERVICE_NAME; } ----------------------------------------------------- @Configuration @EnableConfigurationProperties(HelloServiceProperties.class) @ConditionalOnClass(HelloService.class) @ConditionalOnProperty(prefix = "hello",value = "enable",matchIfMissing = false) public class HelloServiceAutoConfiguration{ } ----------------------------------------------------- @RestController public class ConfigurationPropertiesController{ @Autowired private HelloServiceProperties helloServiceProperties; @RequestMapping("/getObjectProperties") public Object getObjectProperties(){ System.out.println(helloServiceProperties.getMsg()); return myConfigTest.getProperties(); } }
Auto configuration settings
service.properties.name=my-test-name service.properties.ip=192.168.1.1 service.user=keyle service.port=8080
Everything is normal, but if the HelloServiceAutoConfiguration header does not use @ EnableConfigurationProperties, the test access will report an error.
- Do not use @ EnableConfigurationProperties to register, use @ Component to register
@ConfigurationProperties(prefix = "service.properties") @Component public class HelloServiceProperties{ private static final String SERVICE_NAME = "test-service"; private String msg = SERVICE_NAME; public String getMsg(){ return msg; } public void setMsg(String msg){ this.msg = msg; } }
The Controller remains unchanged and everything is normal. If @ Component is commented out, an error will be started
This proves that both methods load the class modified by @ ConfigurationProperties into the Spring container
9. @Param
effect:
When using annotations to simplify XML configuration (such as the introduction of sql parameters in Mapper.xml of MyBatis), the @ Param annotation is used to name the parameters. After the parameters are named, the parameter values can be obtained according to the name, and the parameters can be correctly passed into sql statements (generally through #{}, ${} will have sql injection problems).
Example description:
-
Use @ Param annotation
Mapper interface method:
public int getUserDetail(@Param("userid") int userid);
corresponding Sql Mapper.xml File:
<select id="getUserDetail" statememtType="CALLABLE" resultMap="baseMap"> Exec WebApi_Get_CustomerList #{userid} </select>
explain:
When you use @ Param annotation to declare parameters, you can use #{} or ${}. When you do not use @ Param annotation to declare parameters, you must use #{}. If you use ${}, an error will be reported.
-
Do not use @ Param annotation
When @ Param annotation is not used, it is better to pass Java beans. In SQL statements, you can directly refer to the properties of Java beans, and you can only refer to the existing properties of Java beans.
Mapper interface method:
public int getUserDetail(User user);
corresponding Sql Mapper.xml File:
<!-- Here, you can directly reference the object attribute, and there is no need for the object.Attribute mode --> <select id="getUserDetail" statementType="CALLABLE" resultMap="baseMap"> Exec WebApi_Get_CustomerList #{userid} </select>
10. @Transactional
@Transactional is one of the most commonly used annotations in spring. Usually, we add this annotation when we need to add a transaction to a service method. If an unchecked exception is sent, a rollback will occur. The most typical examples are as follows.
@Service public class StudentService { @Autowired StudentDao studentDao; @Transactional public void innerSave(int i) { Student student = new Student(); student.setName("test" + i); studentDao.save(student); // If i=5, there will be an exception int a = 1 / (i - 5); } }
When innerSave(5) is called, an operation exception will occur, resulting in the rollback of the save operation, which is not described here.
New requirement: save 10 students circularly, and roll back when an exception occurs.
We naturally wrote the following code in studentservice Java add the following methods:
public void outerLooper1() { for(int i = 1; i <= 10; i++) { try { innerSave(i); } catch (Exception e) { e.printStackTrace(); } } }
First consider whether test5 has been saved by this student?
result:
It still appears. What's the problem?
In fact, it's easy to understand that the transaction opening of @ Transactional in spring is created based on the agent of interface or class. Therefore, in the same class, a common method outerLooper1() calls another method innerSave() with transaction, and the transaction will not work. To solve this problem, I usually write a help class and inject it into the current class to complete the transaction operation.
@Autowired UtilService utilService; public void outerLooper2() { for(int i = 1; i <= 10; i++) { utilService.innerSave(i); } }
Using transactions in Spring requires following some specifications and understanding some pitfalls. Don't take it for granted. List some precautions.
Adding @ Transactional annotation where transaction management is needed can be applied to interface definitions and interface methods, class definitions and public methods of classes.
@Transactional annotations can only be applied to public visibility methods. If you use @ transactional annotation on protected, private or package visible methods, it will not report an error, but the annotated method will not display the configured transaction settings.
The Spring team recommends using @ Transactional annotations on specific classes (or methods of classes), rather than on any interface that the class needs to implement. Using the @ Transactional annotation on an interface takes effect only when you set up an interface based proxy. Because annotations cannot be inherited, this means that if a class based proxy is being used, the transaction settings will not be recognized by the class based proxy, and the object will not be wrapped by the transaction proxy.
@Transactional transactions are opened, and either interface based or class based proxies are created. Therefore, if a method calls another method with transaction in the same class, the transaction will not work.
Understand the isolation level of transactions. The default isolation level of each database is different. In spring, isolation = isolation is used READ_ Commit to set.
Understand the propagation mechanism of transactions. When transaction nesting occurs, select the corresponding propagation mechanism according to the business and use propagation = propagation Required to set.