Spring development common annotation record

Spring part

1. Declare the annotation of the bean

@Component component, there is no clear role
Role: placed on the class, it means that this class is managed by the spring container, and objects created by spring are placed in the container

Attribute: The id of the default bean is: the name of the class, the first letter is lowercase

/**
 * 账户类
 */
@Component
public class Account {
    
    
    private Integer id;   //编号
    private String name;   //姓名
    private Double money;  //余额

    @Override
    public String toString() {
    
    
        return "Account{" +
                "id=" + id +
                ", name='" + name + '\'' +
                ", money=" + money +
                '}';
    }
}

@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 to control the life of the layer.
The functions of these three tags are the same as @Component, but they are semantically different.

2. Injection of bean annotations

@Autowired:

  1. Match by type
  2. If there are multiple same types, match by name
  3. If the name is not found, an exception
    is thrown . Location: 1. Member variable 2. Member method

effect:

  • By default, the corresponding object is found from the container by type matching, and injected into this attribute or method
  • If there are multiple of the same type, inject the object by name matching
@Component("user")
public class User1 {
    
    

    @Autowired
    private String username;

    @Override
    public String toString() {
    
    
        return "User{" +
                "username='" + username + '\'' +
                '}';
    }
}

3.Java configuration class related solutions

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

@Bean annotation on the method, declare that the return value of the current method is a bean, instead of the way in xml (on the method)

@Configuration declares that the current class is a configuration class, in which @Component annotations are combined internally, 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 a combination annotation of @Configuration and @ComponentScan, which can replace these two annotations

4. Aspects (AOP) related solutions

Spring supports the annotated aspect programming of AspectJ

@Aspect declares an aspect (on the class)

Use @After, @Before, and @Around to define advice, and you can directly use interception rules (points of cut) as parameters.

@After is executed after the method is executed (on the method)

@Before is executed before the method is executed (on the method)

/**
 * 次要的业务:切面类
 */
@Component  //把这个类加到Spring容器中
@Aspect  //这个类是切面类
public class LogAspect {
    
    

    @Pointcut("execution(* com.itheima.service..*.*(..))")   //切面表达式,这是一个空方法,作用:创建切面表达式的
    public void pt() {
    
    
    }

    @Before("pt()")
    public void before() {
    
    
        System.out.println("前置通知");
    }

    @AfterReturning("pt()")
    public void afterReturn() {
    
    
        System.out.println("后置通知");
    }

    @AfterThrowing("pt()")
    public void afterThrowing() {
    
    
        System.out.println("异常通知");
    }

    @After("pt()")
    public void after() {
    
    
        System.out.println("最终通知");
    }
}

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

/**
 * 次要的业务:切面类
 */
@Component  //把这个类加到Spring容器中
@Aspect  //这个类是切面类
public class LogAspect {
    
    

    @Pointcut("execution(* com.itheima.service..*.*(..))")   //切面表达式,这是一个空方法,作用:创建切面表达式的
    public void pt() {
    
    
    }
  
    /**
     * 环绕通知
     */
    @Around("pt()")
    public Object around(ProceedingJoinPoint joinPoint) {
    
    
        Object result = null;
        try {
    
    
            System.out.println("前置通知");
            //调用目标方法
            result = joinPoint.proceed();
            System.out.println("后置通知");
        } catch (Throwable throwable) {
    
    
            throwable.printStackTrace();
            System.out.println("异常通知");
        } finally {
    
    
            System.out.println("最终通知");
        }
        //返回方法的返回值
        return result;
    }
}

@PointCut declares the point of cut

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

5.@Bean attribute support

@Scope sets how to create a new Bean instance in the Spring container (in the method, @Bean is required)

@Component("user")
@Scope("prototype")
public class User5 {
    
    

}

The setting types include:

Singleton (singleton, there is only one bean instance in a Spring container, the default mode),
Protetype (create a new bean for each call),

Request (in the web project, create a new bean for each http request),

Session (in the web project, create a bean for each http session),

GlobalSession (create a 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, which is equivalent to the bean initMethod in the xml configuration file

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

6.@Value annotation

@Value injects value for the attribute

The following injection methods are supported:

Inject ordinary characters

@Value("Kobe")
String name;

Inject operating system properties

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

Inject configuration files

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

How to use injection configuration:

① Write the configuration file (test.properties)

book.name=《三体》

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

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

③ Need to configure a bean of PropertySourcesPlaceholderConfigurer.

7. Test related solutions

@RunWith runner, usually used in Spring to support JUnit

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

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml")
public class TestAccount {
    
    

    @Autowired
    private AccountService accountService;

    @Test
    public void testUpdate() {
    
    
        //System.out.println(accountService.getClass());
        //获取业务对象,执行业务方法
        accountService.update("Jack");
    }

}

SpringMVC part

@EnableWebMvc Enable Web MVC configuration support in the configuration class, such as some ViewResolver or MessageConverter, etc. If there is no such sentence, rewrite the WebMvcConfigurerAdapter method (used to configure SpringMVC).

@Controller declares that this class is a Controller in SpringMVC

@RequestMapping is used to map Web requests, including access paths and parameters (on classes or methods)

@ResponseBody supports putting the return value in the response instead of a page, usually the user returns json data (next to the return value or on the method)

@RequestBody allows the parameters of the request to be in the request body instead of being directly connected after the address. (Put before the parameters)

@Controller
public class JsonController {
    
    


    //返回的是一个java对象,然后把java对象转换json.
   //请求参数是json字符串的时候需要转换为java对象,那么需要使用@RequestBody
    //如果返回值需要返回的是一个json对象,那么只需要添加@repsonseBody注解即可
    @RequestMapping("/jsonData")
    @ResponseBody
    public User jsonData(@RequestBody  User user){
    
    
        System.out.println("接收到的对象:"+user);
        User user2 = new User(220,"狗剩");
        return user2;
    }

}

@PathVariable is used to receive path parameters, such as the path declared by @RequestMapping("/hello/{name}"). The value can be obtained before the annotation is released in the parameter. It is usually used as an interface implementation method of Restful.

 //查询单个
    /*
       {参数名称}: 参数占位符
       @PathVariable: 获取请求路径的参数给形参注入
     */
    @RequestMapping(value="/{id}/{name}",method= RequestMethod.GET)  //限制该方法只能是post请求访问
    public String findByCondition(@PathVariable("id") Integer id, @PathVariable("name") String name){
    
    
        System.out.println("id:"+id+" 姓名:"+ name);
        return "success";
    }

@RestController This annotation is a combination annotation, which is equivalent to a combination of @Controller and @ResponseBody. The annotation is on the class, which means that all methods of the Controller are added with @ResponseBody by default.

@ControllerAdvice Through this annotation, we can place the global configuration of the controller in the same place. The methods of the class annotated with @Controller can be annotated with @ExceptionHandler, @InitBinder, and @ModelAttribute.
This is annotated to all @ The method in the RequestMapping controller is valid.

@ExceptionHandler is used to handle exceptions in the controller globally

@InitBinder is used to set up WebDataBinder, and WebDataBinder is used to automatically bind foreground request parameters to the Model.

The original function of @ModelAttribute is to bind key-value pairs to the Model. In @ControllerAdvice, the global @RequestMapping can obtain the key-value pairs set here.

Guess you like

Origin blog.csdn.net/weixin_46011971/article/details/108060506