spring, springMVC, mybatis annotations

SSM annotations

1. Mybatis annotations

  • @Param: used to pass parameters so that they can correspond to field names in SQL
  • @Insert: Implement new addition, instead of
  • @Delete: Implement deletion instead of
  • @Update: Implement updates instead of
  • @Select: implements query instead of
  • @Result: Implement result set encapsulation instead of
  • @Results: Can be used together with @Result to encapsulate multiple result sets instead of
  • @One: Implement one-to-one result set encapsulation instead of
  • @Many: Implement one-to-many result set encapsulation instead of

2. Spring annotations

1. Annotations for declaring beans

@Component component, no clear role

@Service is used in the business logic layer (service layer)

@Repository is used in the data access layer (dao layer)

@Controller is used in the presentation layer, and the declaration of the controller

2. Inject bean annotations

**@Autowired:** Provided by Spring

**@Inject:** Provided by JSR-330

@Resource: Provided by JSR-250

**@Qualifier:**Specify the class name injected from spring

As follows, the class named userRealm will be injected from spring

public DefaultWebSessionManager getDefaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
    DefaultWebSessionManager sessionManager = new DefaultWebSessionManager();
    return sessionManager;
}

Both can be annotated on set methods and attributes. It is recommended to annotate on attributes (clear at a glance and write less code).

3.Related notes on java configuration class

@Configuration declares the current class as a configuration class, which is equivalent to Spring configuration in xml form (on the class)

The @Bean annotation is on the method and declares that the return value of the current method is a bean. If the bean name is not written, the default method name is the name of the bean. It replaces the method in xml (on the method)

@Configuration declares the current class as a configuration class, which is internally combined with the @Component annotation, indicating that this class is a bean (on the class)

@ComponentScan is used to scan Component, which is equivalent to (on class) in xml

@WishlyConfiguration is the combined annotation of @Configuration and @ComponentScan, which can replace these two annotations.

4. Aspect (AOP) related notes

Spring supports AspectJ’s annotation aspect programming.

@Aspect declares an aspect (on the class)
Use **@After, @Before, @Around** to define advice, and you can directly use the interception rule (cut point) as a parameter.

@Before is executed before the method is executed (on the method)
@Around is executed before and after the method is executed (on the method)

@PointCut declares pointcuts
Use the @EnableAspectJAutoProxy annotation in the java configuration class to enable Spring’s support for the AspectJ proxy (on the class)

5.@Bean attribute support

@Scope sets how the Spring container creates a new Bean instance (in terms of method, @Bean is required)
Setting types include:

Singleton (single case, there is only one bean instance in a Spring container, default mode),
Protetype (a new bean is created each time the prototype is called),
Request (in web projects, create a new bean for each http request),
Session (in web projects, create a new bean for each http session),
GlobalSession (create a new Bean instance for each global http session)

@StepScope is also involved in Spring Batch

@PostConstruct is provided by JSR-250 and is executed after the constructor is executed. It is equivalent to the initMethod of the bean in the xml configuration file.

@PreDestory is provided by JSR-250 and is executed before the bean is destroyed. It is equivalent to the destroyMethod of the bean in the xml configuration file.

6.@Value annotation

@Value injects a value into the property (on the property)
Supports injection in the following ways:
》Inject ordinary characters

@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 randomNumber;

》Inject other bean properties

@Value("#{domeClass.name}")
String name;

》Inject file resources

@Value("classpath:com/hgs/hello/test.txt")
String Resource file;

》Inject website resources

@Value("http://www.cznovel.com")
Resource url;

》Inject configuration file

@Value("${book.name}")
String bookName;

Injection configuration usage:
① Write configuration file (test.properties)

book.name=《Three-body》

② @PropertySource loads the configuration file (on the class)

@PropertySource(“classpath:com/hgs/hello/test/test.propertie”)

③ You also need to configure a PropertySourcesPlaceholderConfigurer bean.

7. Environment switching

@Profile sets the configuration environment that the current context needs to use by setting the ActiveProfiles of Environment. (on class or method)

In @ConditionalSpring4, you can use this annotation to define a conditional bean. By implementing the Condition interface and overriding the matches method, you can decide whether the bean is instantiated. (Method)

8. Asynchronous related

In the @EnableAsync configuration class, support for asynchronous tasks is enabled through this annotation, narrative AsyncConfigurer interface (on the class)

@Async Use this annotation on the actually executed bean method to declare that it is an asynchronous task (all methods on the method or class will be asynchronous, and @EnableAsync is required to enable asynchronous tasks)

9. Scheduled tasks related

@EnableScheduling is used on the configuration class to enable support for scheduled tasks (on the class)

@Scheduled to declare that this is a task, including cron, fixDelay, fixRate and other types (in terms of method, support for scheduled tasks needs to be enabled first)

10.@Enable annotation description

These annotations are mainly used to enable support for xxx.
@EnableAspectJAutoProxy turns on support for AspectJ automatic proxy

@EnableAsync turns on support for asynchronous methods

@EnableScheduling turns on support for scheduled tasks

@EnableWebMvc turns on Web MVC configuration support

@EnableConfigurationProperties enables support for @ConfigurationProperties annotation configuration beans

@EnableJpaRepositories turns on support for SpringData JPA Repository

@EnableTransactionManagement turns on support for annotated transactions

@EnableTransactionManagement turns on support for annotated transactions

@EnableCaching enables annotation caching support

11. Notes on testing

@RunWith runner, commonly used in Spring to support JUnit

@ContextConfiguration is used to load the configuration ApplicationContext, where the classes attribute is used to load the configuration class

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes={TestConfig.class})
public class KjtTest {
    private static Logger logger = LoggerFactory.getLogger("KjtTest");
    @Autowired
    Service service;
    @Test
    public void test() {
    }
}

3. SpringMVC annotations

3.1 Parameter binding annotations
1.@RequestParam

For the data submitted by the GET method

http://localhost:8080/user?user_id=1

You can get the values corresponding to the following parameters through the following method:

@GetMapping("/user") //Note that the request path is written differently here
public String testRequestParam(@RequestParam(user_id) Integer id) {
    System.out.println("The obtained id is: " + id);
    return "success";
}

For the data requested by the Post method

Add the front end to submit the username and password parameters through the form name attribute in the post, then we can use @RequestParam to receive them

 public int getUsersDetail(@RequestParam("username ") String name,@RequestParam("password ") String pwd );
2.@RequestBody

The RequestBody annotation is used to receive entities from the front end, and the received parameters are also corresponding entities. For example, the front end submits two parameters, username and password, through JSON. At this time, we need to encapsulate an entity in the back end to receive it. When there are many parameters passed, it is very convenient to use @RequestBody to receive them. For example: the code that defines the User class is omitted here…

@PostMapping("/user")
public String testRequestBody(@RequestBody User user) {
    System.out.println("The username obtained is: " + user.getUsername());
    System.out.println("The password obtained is: " + user.getPassword());
    return "success";
}

RequestParam: What is received is the data in the request header, which is the key-value get request entered in the URL in the browser.
RequestBody: What is received is the data in the request body, that is, the data sent by the post request.

3.@PathVariable

Mainly to obtain Restful style URL parameters. For example, a GET request carries a parameter id. We receive the id as a parameter and can use the @PathVariable annotation. as follows:

http://localhost:8080/test/user/2/zhangsan

@GetMapping("/user/{idd}/{name}")
    public String testPathVariable(@PathVariable(value = "idd") Integer id, @PathVariable String name) {
        System.out.println("The obtained id is: " + id);
        System.out.println("The name obtained is: " + name);
        return "success";
    }

The console outputs the following information:
The obtained id is: 21
The obtained name is: zhangsan
3.2 Other types of annotations
1.@Controller

In SpringMVC, the controller is mainly responsible for processing requests sent by the front-end controller (DispatcherServlet). After processing by the business logic layer, it encapsulates a model and returns it to the view for display. The @controller annotation is usually used on classes. If used in conjunction with Thymeleaf templates, a page will be returned. If it is a project with separate front and back ends, use @RestController to indicate that json format data is returned.

2.@ResponseBody

Annotations convert the returned data structure into JSON format

3.@RestController

Contains @Controller annotation and @ResponseBody annotation

4.@RequestMapper

Annotations for handling request address mapping

The knowledge points of the article match the official knowledge files, and you can further learn related knowledge. Java Skill TreeHomepageOverview 138735 people are learning the system