Spring Annotation's Road to Progress-Super Detailed Explanation

I. Introduction

Spring is an important framework knowledge point that we cannot avoid when learning Java. The core knowledge points in spring are IOC and AOP. The main IOC inversion of control is to initialize and load the Bean into the container, but how is the Bean? Loaded into the container, here we can use spring annotations or spring XML configuration to achieve.

The Spring annotation method reduces the content of the configuration file, which is more convenient for our project management, and the use of annotations can greatly improve our development efficiency!

Below we introduce some commonly used annotations in spring.

Two: component class annotation

@component: Annotate a common spring Bean class. @Repository: Annotate a Dao component class. @service: Annotate a business logic component class. @Controller: Annotate a controller component class. These are some of the annotations that are used relatively high in the usual development. These annotations are essentially the same type of annotations, with the same usage and the same function, and the difference lies in the different types of components identified. @component can replace @Repository, @Service, @Controller, because these three annotations are marked by @Component. code show as below

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller{
    string  value()  default “”;
    }

image

②: Detailed examples

  • When a component represents the data access layer (Dao), we use @Repository for annotation, as follows
@Repository
public class HappyDaoImpl implements HappyDao{
private final static Logger LOGGER = LoggerFactory.getLogger(HappyDaoImpl .class);
public void  club(){
        //do something ,like drinking and singing
    }
}
  • When a component represents the business layer, we use @Service for annotation, as follows
@Service(value="goodClubService")
//使用@Service注解不加value ,默认名称是clubService
public class ClubServiceImpl implements ClubService {
    @Autowired
    private ClubDao clubDao;
  
    public void doHappy(){
        //do some Happy
    }
 }
  • When a component is used as the control layer for front-end interaction, it is annotated with @Controller, as follows
@Controller
public class HappyController {
	@Autowired //下面进行讲解
    private ClubService clubService;
    
	// Control the people entering the Club
	// do something
}
/*Controller相关的注解下面进行详细讲解,这里简单引入@Controller*/

③: Summary

The java class in the remarks is treated as a Bean instance, and the name of the Bean instance is the initial small letter of the Bean class by default, and other parts remain unchanged. @Service can also customize the Bean name, but it must be unique: 2. Try to replace the @Component annotation with the corresponding component annotation class. In future versions of Spring, @Controller, @Service, and @Resposity will carry more semantics. And easy to develop and maintain! 3. After specifying that certain classes can be used as spring Bean classes, it is better to let spring search for the specified path and add the following configuration in the spring configuration file:

<!-- 自动扫描指定包及其子包下的所有Bean类 -->
<context:component-scan base-package="org.springframework.*"/>

Three: Commonly used annotations when assembling beans

①: Annotation introduction

@Autowired: belongs to spring's org.springframework.beans.factory.annotation package, which can be used to annotate class attributes, constructors, and methods @Resource: does not belong to spring annotations, but comes from JSR-250 in java Under the .annotation package, use the annotation to specify the collaborator bean for the target bean. The @postConstruct and @preDestory methods implement the operations performed before the bean is initialized and destroyed.

②: Examples

@Autowired

@Target({ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, 
ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
    boolean required() default true;
}
@Controller
public class HappyController {
	@Autowired //默认依赖的ClubDao 对象(Bean)必须存在
	//@Autowired(required = false) 改变默认方式
	@Qualifier("goodClubService")
    private ClubService clubService;
    
	// Control the people entering the Club
	// do something
}
  • @Resource
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
 String name() default "";
 Class type() default java.lang.Object.class;
public class AnotationExp {
    @Resource(name = "HappyClient")
    private HappyClient happyClient;
    
    @Resource(type = HappyPlayAno .class)
    private HappyPlayAno happyPlayAno;
}

③: Summary

  • Similarities: @Resource is equivalent to @Autowired, and can be marked on the setter method of a field or property.

  • Differences: The provider @Autowired is spring annotation, @Resource is javax.annotation annotation, but it comes from JSR-250, provided by J2EE, and requires JDK1.6 or higher.

  • The injection method @Autowired is only injected according to Type; @Resource is automatically injected according to Name by default, and injection according to Type is also provided

  • Properties: @Autowired annotation can be used to annotate the properties, constructors, and methods of the class. By default, the objects that the device depends on must exist (beans are available). If you need to change this default method, 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 multiple beans of the same type, an exception that the specified type of bean cannot be found will be reported when the container is started, and the solution should be combined with **@ The Qualifier** annotation is qualified and specifies the name of the injected bean.

  • @Resource has two important attributes, name and type. The name attribute specifies byName. If the name attribute is not specified, when the annotation is marked on the field, the name of the field is read by default as the bean name to find the dependent object. When the annotation is marked on the setter method of the property, the attribute name is taken as the bean name by default Look for dependent objects. It should be noted that the @Resource annotation will fall back to assembly by type. But once the name attribute is specified, it can only be assembled by name.

  • The use of @Resource annotation is more flexible, you can specify the name, you can also specify the type; @Autowired annotation is easy to throw exceptions for assembly, especially when there are multiple bean types to be assembled, and the annotation method needs to add @Qualifer Qualify.

               [Spring中 @Autowired注解与@Resource注解的区别](http://qiangmzsx.blog.51cto.com/2052549/1359952)
    

Note: When using @Resource, you should also pay attention to adding configuration files to spring, if component-scan is not configured

<context:component-scan> 
<!--<context:component-scan>的使用,是默认激活<context:annotation-config>功能-->

You must configure annotation-config

<context:annotation-config/>

四:@Component vs @Configuration and @Bean

①: Brief introduction

The official team of spring says that @Component can replace @Configure annotations. In fact, we can also find out by looking at the source code, as follows

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component  //看这里!!!
public @interface Configuration {
    String value() default "";

Although it can be substituted, there is still a difference between the two annotations!
As long as Bean annotation is used on methods, it is a bit similar to factory work. When using @Bean annotation, we can continuously use multiple annotations that are used to define beans. For example, @Qualifier annotation is used to define the name of the factory method, and @Scope annotation is used. Define the scope of the bean, such as singleton or prototype.

The core of the new Java configuration support in Spring is the @Configuration annotated class. These classes mainly include @Bean annotated methods to define instances, configuration and initialization logic for objects managed by spring's IOC container

Using @Configuration to annotate a class means that it can be used by spring's IOC container as a resource for bean definition.

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

This is very similar to the spring xml file

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

The @Bean annotation plays the same role as the element.
②: Illustrate @Component and @Configuration

@Configuration
public static class Config {
    @Bean
    public SimpleBean simpleBean() {
        return new SimpleBean();
    }
    @Bean
    public SimpleBeanConsumer simpleBeanConsumer() {
        return new SimpleBeanConsumer(simpleBean());
    }
}
@Component
public static class Config {
    @Bean
    public SimpleBean simpleBean() {
        return new SimpleBean();
    }
    @Bean
    public SimpleBeanConsumer simpleBeanConsumer() {
        return new SimpleBeanConsumer(simpleBean());
    }
}

The first code works, as expected, SimpleBeanConsumer will get a link to the singleton SimpleBean. The second configuration is completely wrong, because Spring will create a SimpleBean singleton bean, but SimpleBeanConsumer will get another SimpleBean instance (which is equivalent to calling new SimpleBean() directly, this bean is not managed by Spring), Both the new SimpleBean() instance is outside the Spring context control

③: Summary of reasons

Use @configuration, so the method marked as @bean will be wrapped into a CGLIB wrapper. It works like the first call of this method, then the original body will be executed, and the final object will be in the spring context registered. All further calls only return the beans retrieved from the context.

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

@Component
public static class Config {
    @Autowired
    SimpleBean simpleBean;

    @Bean
    public SimpleBean simpleBean() {
        return new SimpleBean();
    }

    @Bean
    public SimpleBeanConsumer simpleBeanConsumer() {
        return new SimpleBeanConsumer(simpleBean);
    }
}

Spring @Configuration vs @Component
basic concepts: @Configuration and @Bean

Five: Spring MVC module annotation

①: Annotations commonly used in web modules

  • @Controller: Indicates that this class will act as a control layer component that interacts with the front end, providing a behavior defined by the service interface to access the application, interpreting the user's input, converting it into a model, and then trying to present it to the user.
@Controller
public class HappyController {
	//do something
...
}

Spring MVC uses @Controller to define controllers. It also allows automatic detection of components defined in the classpath (scan path configured in the configuration file) and automatic registration.

  • @RequestMapping: This annotation is used to map the URL to the entire processing class or specific request processing method. You can use only wildcards!
@Controller
@RequestMapping("/happy")
public class HappyController  {
  @Autowired
  private HappyService happyService;
  
  @RequestMapping(/hello/*)
  public void sayHello(){
		//请求为 /happy/hello/* 都会进入这个方法!
		//例如:/happy/hello/123   /happy/hello/adb
		//可以通过get/post 请求
  }
  @RequestMapping(value="/haha",method=RequestMethod.GET)
  public void sayHaHa(){
  //只能通过get请求
  }
...
}

@RequestMapping can be applied to both the class level and the method level. When it is defined at the class level, it indicates that all requests processed by the controller are mapped to the /favsoft path. @RequestMapping can use the method attribute to mark the method type it accepts. If the method type is not specified, the HTTP GET/POST method can be used to request data, but once the method type is specified, the data can only be obtained using that type.

  • @RequestParam: Bind the requested parameters to the parameters in the method. There is a required parameter. By default, required=true, which means that the parameter must be passed. If you change the parameter, you can pass it or not, you can configure required=false .
 @RequestMapping("/happy")
  public String sayHappy(
  @RequestParam(value = "name", required = false) String name,
  @RequestParam(value = "age", required = true) String age) {
  //age参数必须传 ,name可传可不传
  ...
  }
  • @PathVariable: This annotation is used to modify method parameters, which will change the modified method parameters into available uri variables (which can be used for dynamic binding).
@RequestMapping(value="/happy/{dayid}",method=RequestMethod.GET)
public String findPet(@PathVariable String dayid, Model mode) {
//使用@PathVariable注解绑定 {dayid} 到String dayid
}

The parameters in @PathVariable can be any simple type, such as int, long, Date, etc. Spring will automatically convert it to the appropriate type or throw a TypeMismatchException. Of course, we can also register to support additional data types.
@PathVariable supports the use of regular expressions, which determines its super powerful properties. It can use placeholders in path templates, and can set specific prefix matching, suffix matching and other custom formats.

  • @RequestBody: @RequestBody means that method parameters should be bound to the HTTP request Body.
@RequestMapping(value = "/something", method = RequestMethod.PUT)
public void handle(@RequestBody String body,@RequestBody User user){
   //可以绑定自定义的对象类型
}

@ResponseBody: @ResponseBody is similar to @RequestBody, its function is to directly enter the return type into the HTTP response body.

  • @ResponseBody is often used when outputting data in JSON format.
@RequestMapping(value = "/happy", method =RequestMethod.POST)
@ResponseBody
public String helloWorld() {    
return "Hello World";//返回String类型
}

@RestController: The controller implements the REST API, only to serve JSON, XML or other custom types of content, @RestController is used to create REST type controllers, and @Controller type. @RestController is such a type, it avoids you from writing @RequestMapping and @ResponseBody repeatedly.
@ModelAttribute: @ModelAttribute can act on a method or method parameter. When it acts on a method, it indicates that the purpose of the method is to add one or more model attributes.

This method supports the same parameter types as @RequestMapping, but it cannot be directly mapped to a request. The @ModelAttribute method in the controller will be called before the @RequestMapping method is called.

The @ModelAttribute method has two styles: one is to add an invisible attribute and return it. The other is that the method accepts a model and adds any number of model attributes. Users can choose the corresponding style according to their needs.

Six: Spring transaction module annotation

①: frequently used notes

When dealing with transaction operations at the dao layer or service layer, such as the rollback operation when the deletion fails. Use **@Transactional** as an annotation, but it needs to be activated in the configuration file

<!-- 开启注解方式声明事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

②: Example

@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;
  }
  ...
}

③: Summary

Transaction propagation mechanism and isolation mechanism are more important!

image

A picture to learn Spring transaction propagation

readOnly: The read and write attributes of the transaction, which can be true or false, true is read-only, and the default is false

rollbackFor: Rollback strategy, rollback when encountering a specified exception. For example, if the above example encounters an exception, it will roll back

timeout (Supplementary): Set the timeout time in seconds

isolation: set transaction isolation level, enumerated type, a total of five

image

Thoroughly grasp the use of @transactional in  Spring Spring transaction configuration and transaction propagation and isolation level

Seven: Reference blog post

Original link: https://blog.csdn.net/u010648555/article/details/76299467

Guess you like

Origin blog.csdn.net/qq_44762290/article/details/107529356