Ten, Spring commonly used annotation - layered finishing

1, @ Controller: mark the presentation layer components (Bean), but this feature is currently @Component with the same process used to create the http request object
   annotation added after Spring4, had returned in json in @Controller @ResponseBody need to cope with, if Alternatively directly @RestController @Controller not necessary to configure @ResponseBody, default
return json format
1.1) @RequestMapping
    class definition at: provide initial request mapping information relative to the root of the WEB application. The method: to provide a further breakdown map information with respect to the class definition at the URL.
    Column shows. 1:
    @Controller
    @RequestMapping ( "/ fourthPage")
    public class {} FourthPageController the extends CommonController
    
    shown Column 2: .do comprising, when the access path is not included .do suffix will be given 404
    @RequestMapping (value = "/ getLogo.do ")
    @ResponseBody
    public void getLogo (the HttpServletRequest Request, the HttpServletResponse Response) throws IOException {}
    
    shows column 3: do not contain
    @RequestMapping(value = "/ajax/itemParameter/{partNumber:[\\d]+}_{cateGoryCode}","/ajax/itemPackageDetail/{supplierCode:[\\d]+}/{partNumber:[\\d]+}"})
    public String itemParameter(@RequestParam(value = "callback", required = false) String callback,
                                @PathVariable("partNumber") String partNumber,
                                @PathVariable("cateGoryCode") String cateGoryCode,
                                @RequestParam(value = "channel", required = false) String channel,
                                HttpServletResponse response) {

    分析:
    a. @RequestMapping使用正则表达式
    @RequestMapping(value = "/ajax/itemParameter/{partNumber:[\\d]+}_{cateGoryCode}")
    partNumber: [\\ d] + represents: partNumber must pass a digital value, matching one or more times, not Ruoguo
    b @RequestMapping the request value is 2, represent two different requests that a common method.
   
1.2 ) @RequestParam
    for mapping data request parameter area to the processing method parameter is inconsistent if the received parameter name and passed over the interface, a can may be received in the following manner.
    payWay interfaces parameter is passed, channel mapping parameter is the name of payWay
    @RequestMapping (value = "/itemInfo.do")
    @ResponseBody
    public String itemParameter (@RequestParam (value = "payWay", required to false =) String Channel) {
    
    }
    

1.3) @ModelAttribute
    shown column 1: the method is used to return:
    when ModelAttribute set value, the method returns the value to the value of key, the value received as the parameter value, is stored in the Model, as described in after performing the method, corresponding to the final model.addAttribute ( "user_name", name) ;
    if no custom @ModelAttribute value, is equivalent model.addAttribute ( "name", name);

    @ModelAttribute (value = "
    String itemParameter public (@RequestParam (value = "Channel", required to false =) String name, the Model Model, the HttpServletResponse Response) {
        return name;
    }
    shown Column 2: no return on the method, it is necessary to manually increase model.addAttribute ( ) method
    @ModelAttribute
    public String itemParameter (@RequestParam (value = "Channel", required to false =) String name, the Model Model, the HttpServletResponse Response) {
        model.addAttribute ( "name", name);
    }
    shows column 3: marking method the parameters
    parameters will be passed over by the client name is injected into the specified object, and the object will be automatically added ModelMap, the ease of use View layer.
    @RequestMapping (value = { "/ Ajax / itemPackageDetail / {the partNumber: [ \\ d] +} "," / ajax / itemPackageDetail / {supplierCode: [\\ d] +} / {partNumber: [\\ d] +} "})
    String queryPackageDetail public (@RequestParam (value = "callback", required = false) String callback,
                                     @PathVariable ( "partNumber") String partNumber,
                                     @ModelAttribute ( "supplierCode") String supplierCode,
                                     @RequestParam (value = "Channel", required to false =) String Channel,
                                     the HttpServletResponse Response) {}
                                        
    
1.4) @PathVariable ( "partNumber")
    can placeholders in the URL parameters @PathVariable {partNumber} method to bind to the processor in the class parameter @PathVariable ( "partNumber ")
    Note: See the article https://mp.weixin.qq.com/s/wImduUsyy0dG0ZawmZab4g

2) @Service: labeling business layer components (Bean), but now the same function @Component
    shown column:
    @Service ( "productSearchService")
    @Implement (Contract = ProductSearchService.class)
    public class ProductSearchServiceImpl the implements ProductSearchService {
        @Autowired
        @Qualifier ( "jedisClient")
        Private JedisClientImpl jedisClient;
        
        @Autowired
        Private CategoryBusiness categoryBusiness;
        
    }
    

. 3) @Repository: annotation storage layer component (Bean)
   Import org.springframework.stereotype.Repository;
   to make Spring classpath can scan and identify classes @Repository annotation, enable auto scan function Bean in the XML configuration file, which can be context by <: component -
   Scan /> achieve
   
   @Repository DAO class can only be marked on it? This is because not only the effect of the annotation as a class identification Bean, while it can be thrown marked class encapsulates data access exception Spring
   Data access exception type. Spring itself provides a rich and is independent of the access technology specific data structure data access exceptions, for different packages persistence framework thrown exception that iso
   often independent of the underlying framework.
   Column shows:
   @Repository
   public class CmmdtySpecialInfoBusiness {
        @Autowired
        DalClient dalClient;
        
        @Autowired
        @Qualifier ( "cmmdtyDalClientRead")
        protected DalClient cmmdtyDalClientRead;    
   }
  
. 4) @Component is a generalization of the concept, represent only one component (Bean), may act any level   
   
5) @Transactional usually added service layer
        a. a so-called transaction refers to a group that is a set of logical operation unit sql statement. As part of the operation of this unit fails, the entire transaction is rolled back, all right only to complete submission. Determining whether a transaction is successfully configured
    whether the transaction will be rolled back when the key point is abnormal.
        b. If our business notes @Transactional added dao layer, as long as do additions and deletions to the database, it is necessary to submit a transaction, the characteristics of the transaction so do not come out to play, especially in matters
    Consistency, concurrency issues when there is some deviation from the user data will be found in the database. Generally, we can call the service layer dao multiple layers, we only need to add a layer of affairs in the service
    notes @Transactional, so that we can handle multiple requests a transaction, the characteristics of the transaction will be fully realized.

6) @Qualifier notes
        qualifier means that those who pass through this mark, indicating that what we need is implementation class. When EmployeeService interface has two classes serviceImp service1 and service2 time
    if you use EmployeeService @Autowired to be injected, spring will bind because they do not know which implementation class and error. @Qualifier need to distinguish
        shown column:
        @Autowired
        @Qualifier ( "Service1")
        the EmployeeService the employeeService;
    
. 7) and @Resource @Autowired differences:
        . @Autowired A spring is provided annotation, a default byType by injection. byName needs @Qualifier ( "object name") used in conjunction
        used to assemble the bean, can be written in the field, or the method. By default in claim dependent objects must be present, if you want to allow null values, can set its required property is false,
        for example: @Autowired (required = false)

        b. @Resource is JAVA2EE offer, while supporting byType and byName injection, injection byName by default, if you can not find the case of default by type to find (name resolves to attribute name of the bean,
        and the type attribute is resolved to the type of bean , If neither name nor specify the type attribute, then uses the reflection mechanism automatically byName by injection strategy)
    recommended: @Resource annotation on the field, so do not write the setter methods, and this comment is part of J2EE, and reduces the spring of the coupling. Since this code is relatively elegant look. Commonly used @Autowired
        shown column:
            @Resource (name = "auditOrderSubmitServiceImpl")
            Private OrderSubmitService <OrderInfo> auditOrderSubmitServiceImpl;
            
            @Autowired
            Private OrderSubmitBusiness orderSubmitBusiness;
            
            public abstract class CommonBusiness {
                / ** to add, modify, delete, merge operation * /
                @ Resource
                @ Qualifier ( "dalClient")
                DalClient dalClient protected;
                / ** query for * /
                @Resource
                @Qualifier ( "dalClientRead")
                protected DalClient dalClientRead;
            }
    @Resource assembly sequence:
    A If both the name and type, from Spring context unique match is found. the bean assembled, can not find an exception is thrown
    b. If the name is specified, from the context, find the name (id) match bean assembled, can not find an exception is thrown
    c. If the specified type, from find a unique context that matches the type of bean assembled, can not find or find more, will throw an exception
    d If neither name is specified, and no specified type, then automatically assembled according to byName way; if there is no match, then return be a primitive type back system matches the automatic assembly;
   
. 8) to set the spring bean @Scope scope that identifies the scope of the bean. The default is singleton
    a.singleton: Singleton, a global one and only one instance of
    b.prototype: prototype model, every acquisition Bean when there will be a new instance
    c.request: request indicates that for every HTTP request results in a new bean, while the bean is only valid in the current HTTP request
    d.session: session scope means that for every HTTP request will generate a new bean, while the bean is only valid for the session of the current HTTP
    e.global the session: is only useful in portal applications, to each new global http session a Bean instance
   

Guess you like

Origin www.cnblogs.com/jiarui-zjb/p/11420841.html