Detailed notes springmvc common

1、@Controller

In SpringMVC, the distribution of Controller responsible for processing requests from the DispatcherServlet, it requests the user service data after a treatment layer. Package Model, the Model and then returned for display to the corresponding View. In SpringMVC provided in a very simple way to define the Controller, you do not need to inherit a particular class or implement a specific interface, just use @Controller mark a class is Controller, and then use some annotations to define @RequestMapping and @RequestParam etc. URL mapping between the request and the Controller method, this Controller can be accessible to the outside world. Further Controller does not depend directly on HttpServletRequest and HttpServletResponse HttpServlet other objects, which may be a flexible process parameter is acquired by the Controller.

@Controller for marking on a class, which is a class mark SpringMVC Controller object. The processor will distribute a scanning method using the annotation class, and the method detects whether the @RequestMapping annotations. @Controller controller only defines a class, a method using real @RequestMapping annotation process processor requests. @Controller alone are marked on a class can not really say that it is SpringMVC of a controller in the sense of class, because this time the Spring do not even know it. So how do the Spring you can recognize it? This time we need to put this Spring controller class to manage. There are two ways:

  (1) is defined MyController bean objects SpringMVC profile.

  (2) tells the SpringMVC Spring configuration file where to look for the mark @Controller Controller controller.

<! - a way -> 
<the bean class = "com.host.app.web.controller.MyController" /> 
<! - Second way -> 
<context: Component Base-Package-Scan = "COM. host.app.web "/> // path written controller layer (scan package Detailed Analysis see below)

2、@RequestMapping

RequestMapping is a process for annotation request address mapping, it can be used for class or method. For the class, all the methods in response to the request class are represented in the address as the parent path.

RequestMapping notes six attributes, let her be divided into three categories description (below the corresponding example).

1、 value, method;

value: Specifies the physical address of the request, the address may be specified URI Template mode (will be described later);

method: method specifies the type of request, GET, POST, PUT, DELETE and the like;

2、consumes,produces

consumes: submit a request specifying process of the content type (Content-Type), for example, application / json, text / html;

produces: content type of the returned request only if the request header (the Accept) containing the specified type will return to type;

3、params,headers

params: Specifies the request must contain certain parameter values, before allowing the processing method.

headers: Specifies the request must contain certain specified header value, in order for this method to process the request.

3、@Resource和@Autowired

Use @Resource and @Autowired are injected bean do, in fact, not @Resource Spring annotations, its package is javax.annotation.Resource, you need to import, but injected into the Spring annotation support.

1, common

Both can be written in the field and setter methods. If both are written in the field, you do not need to write a setter method.

2, different points

(1)@Autowired

Spring @Autowired annotation is provided, the package need to import org.springframework.beans.factory.annotation.Autowired; only according byType injection.

Copy the code
TestServiceImpl class {public 
    // just use one of two @Autowired to 
    @Autowired 
    Private UserDao userDao; // for the field 
    
    @Autowired 
    the method public void setUserDao (UserDao userDao) { // attributes for 
        this.userDao userDao =; 
    } 
}
Copy the code

@Autowired annotation in accordance with the type (the byType) dependent objects assembled, by default it requires dependent objects must be present, if the null value is allowed, it may be required attribute set to false. If we want to use by name (byName) to assemble, can be combined @Qualifier annotation used together. as follows:

public class TestServiceImpl {
    @Autowired
    @Qualifier("userDao")
    private UserDao userDao; 
}

(2)@Resource

@Resource default automatic injector according ByName provided by the J2EE, need to import the package javax.annotation.Resource. @Resource has two important attributes: name and type, and Spring will @Resource annotation name attribute resolves to the bean's name, the type attribute is resolved to the type of bean. So, if you use the name attribute is used byName automatic injection strategy, and is used when using the type attribute byType automatic injection strategy. If the name is neither developed nor developing type attribute, then the policy will automatically injected using byName by reflection.

Copy the code
TestServiceImpl class {public 
    // just use one of two @Resource to 
    @Resource (name = "userDao") 
    Private UserDao userDao; // for the field 
    
    @Resource (name = "userDao") 
    public void setUserDAO (UserDao userDao) {// attributes for the setter method 
        this.userDao = userDao; 
    } 
}
Copy the code

Note: It is best to @Resource on a setter method, because it is more consistent with object-oriented thinking through the set, get to operate the property, rather than directly to the operating property.

@Resource assembly sequence:

① If you specify the name and type, from the Spring context to find a unique match of bean assembled, can not find an exception is thrown.

② If the name is specified, from the context, find the name (id) match bean assembled, can not find an exception is thrown.

③ If the type is specified, from the context find a unique bean similar matches for assembly, can not find or find more, will throw an exception.

④ If neither specified name, and no specified type, according to the automatic assembly byName manner; if there is no match, then the match is a backoff primitive type, if a match is automatically assembled.

@Resource effect equivalent to @Autowired, but @Autowired automatically injected in accordance with byType.

4、@ModelAttribute和 @SessionAttributes

Representative are: the Controller of all methods before calling, perform this @ModelAttribute method can be used for annotations and method parameters, you can put this @ModelAttribute characteristics, application in BaseController among all Controller inherit BaseController, can be realized in when calling Controller, the first implementation @ModelAttribute method.

 @SessionAttributes value into the session scope is about to write in the class above.

See the following specific example: using @ModelAttribute and save data transfer and @SessionAttributes

5, @ PathVariable

Request for the URL template variable parameter is mapped to a processing method, i.e. extraction uri template variable as a parameter. Such as:

Copy the code
@Controller  
public class TestController {  
     @RequestMapping(value="/user/{userId}/roles/{roleId}",method = RequestMethod.GET)  
     public String getLogin(@PathVariable("userId") String userId,  
         @PathVariable("roleId") String roleId){  
         System.out.println("User Id : " + userId);  
         System.out.println("Role Id : " + roleId);  
         return "hello";  
     }  
     @RequestMapping(value="/product/{productId}",method = RequestMethod.GET)  
     public String getProduct(@PathVariable("productId") String productId){  
           System.out.println("Product Id : " + productId);  
           return "hello";  
     }  
     @RequestMapping(value="/javabeat/{regexp1:[a-z-]+}",  
           method = RequestMethod.GET)  
     public String getRegExp(@PathVariable("regexp1") String regexp1){  
           System.out.println("URI Part 1 : " + regexp1);  
           return "hello";  
     }  
}
Copy the code

6、@requestParam

@requestParam primarily for acquisition parameters SpringMVC background controlling layer, a similar one is request.getParameter ( "name"), which has three common parameters: defaultValue = "0", required = false, value = "isApp"; defaultValue represents set the default value, required copper over whether it is necessary to set the boolean parameter passed in, value value indicates acceptance of an incoming parameter type.

7、@ResponseBody

Action: The Controller annotation for the object returned by the method, by an appropriate body HttpMessageConverter conversion area after a specified data format, and writes the Response object.

When to use it: return to the page data is not html tags, but some other data formats (such as json, xml, etc.);

8、@Component

Equivalent to the common comment when you do not know which layer classes return to use, but not recommended.

9、@Repository

Dao layer for the annotation, annotation daoImpl above category.

 

Note:

1, using the map @RequestMapping Request to request the processor

A way, by the usual methods and class path access path controller binding method

Second way, using the template uri

Copy the code
@Controller 
@RequestMapping ( "/ Test / variable1 {}") 
public class MyController by { 
@RequestMapping ( "/ ShowView / variable2 {}") public ModelAndView ShowView (@PathVariable String variable1, @PathVariable ( "variable2") variable2 int) { = new new ModelAndView ModelAndView ModelAndView (); modelAndView.setViewName ( "viewName"); modelAndView.addObject ( "model needs to be set in the attribute name", "corresponding to the attribute value, it is an object"); return ModelAndView; } }
Copy the code

URI in the URI template is given a variable and then dynamically to the variable assignment when mapping. URI templates such as http: // localhost / app / {variable1} /index.html, this template which contains a variable variable1, then when we request http: //localhost/app/hello/index.html of time, the URL will match with the template, but the template to replace variable1 with a hello. This variable is in use @PathVariable SpringMVC to mark. In SpringMVC, we can use the processing method to mark @PathVariable parameters of a Controller, a value representative of the parameter values ​​used in the URI template corresponding to the variable assignment.

Code URI we define two variables, a controller class is on variable1, variable2 on showView is a method and parameters used in the method of showView inside @PathVariable  labeled using these two variables. So when we use /test/hello/showView/2.do to request access to showView method can MyController, this time it is given the value variable1 hello, variable2 was given a value of 2, then the method parameters which we showView labeled variable1 and variable2 parameters are variables from the path of access paths, this method parameters variable1 and variable2, respectively, was given hello and 2. Variable1 is defined as a method parameter of type String, variable2 is defined as an int type, like making an assignment when this simple type of Spring will help us to automatically convert.

   In the above code, we can see the path variable labeled variable1 is when we are using the @PathVariable, and when used in marking variable2 is @PathVariable ( "variable2"). Both what difference does it? The first case to go to the default template to find the parameter name with the same variable URI, but this is only when using the debug mode before they can be compiled, while the second case is clearly defined use is the URI template variable2 variable. When not using debug mode to compile, or variable name is required to be used with the parameter names are not the same time, we must use the second way is clear that the use of URI template which variable.

 In addition to using URI templates, define variables in addition to the request path, @ RequestMapping also supports wildcard "*" . As the following code I can use /myTest/whatever/wildcard.do access to the Controller testWildcard method. Such as:

Copy the code
@Controller
@RequestMapping ( "/myTest" )
public class MyController {
    @RequestMapping ( "*/wildcard" )
    public String testWildcard() {
       System. out .println( "wildcard------------" );
       return "wildcard" ;
    }  
}
Copy the code

When @RequestParam not specified parameter name, Spring in the code is the same name as the default Parameter take more compilation debug method in the case of, if not the debug compiler will report an error.

2, the use of some advanced usage @RequestMapping

(1) params properties

@RequestMapping (value= "testParams" , params={ "param1=value1" , "param2" , "!param3" })
    public String testParams() {
       System. out .println( "test Params..........." );
       return "testParams" ;
    }

Params @RequestMapping property is specified as the three parameters, which are for purposes of request parameters, which represent the value of the parameter must be equal param1 value1, param2 parameter must be present, the value does not matter, must param3 parameter does not exist, only when /testParams.do request and satisfy the specified condition when the three parameters in order to access to the process. Therefore, when the access request can correctly /testParams.do?param1=value1¶m2=value2 testParams to the method, when the request is not able /testParams.do?param1=value1¶m2=value2¶m3=value3 normal access to this method, the in the params parameter specifies parameters @RequestMapping inside param3 it can not exist.

(2) method attribute

@RequestMapping (value= "testMethod" , method={RequestMethod. GET , RequestMethod. DELETE })
    public String testMethod() {
       return "method" ;
    }

Limits on the use of the method parameters in the request method GET or DELETE / testMethod time to access the Controller to testMethod method in the above code.

(3) headers properties

@RequestMapping (value= "testHeaders" , headers={ "host=localhost" , "Accept" })
    public String testHeaders() {
       return "headers" ;
    }

Use headers and functional properties similar to the params property. In the above code, the time when the request only when /testHeaders.do host Accept request header contains information and the request for the time to properly access the localhost to testHeaders method.

3, @RequestMapping marking method of processors support parameters and return type of the method

1. Method Supported parameter types

         (1) HttpServlet object including HttpServletRequest, HttpServletResponse and HttpSession object. Spring These parameters are automatically assigned to them at the time of call processors process, so when these objects need to use in the process when the processor can be directly stated method parameters given in a method, then the method directly inside body use it. But one thing should be noted that when using HttpSession object, if this time the HttpSession object has not been established, then there will be problems.

   (2) Spring your WebRequest object. This object can be used to access property values stored in the HttpServletRequest and the HttpSession.

   (3) InputStream, OutputStream, Reader and Writer. InputStream and Reader Yes, you can take data from the inside for the purposes of HttpServletRequest; OutputStream and Writer is for the purposes of HttpServletResponse, you can write the data entered.

   (4) use @PathVariable, @ RequestParam, @ CookieValue and @RequestHeader tag parameters.

   (5) @ModelAttribute parameter markers.

   (6) java.util.Map, Spring Model package and ModelMap. These models can be used to encapsulate the data, used to view for display.

   (7) entity class. It can be used to receive the parameters uploaded.

   MultipartFile (8) Spring package. To receive the uploaded file.

   (9) Spring package BindingResult Errors and objects. These two parameters must be the object immediately after the need to verify the physical object parameters, it contains the results of the verification entity object.

2. Support the return type

   (1) and a ModelAndView object model comprises views.

   (2) a model object, which includes a ModelMap Spring packaged and Model, and a java.util.Map, when there is no returned view RequestToViewNameTranslator view name will be determined.

   (3) a View object. If the model at this time in view of the rendering process can be defined if the model parameters to a processor method, and then add to the value of the model in the process of the inside thereof.

   (4) a string String. This often represents a view name. This model requires time if desired during the rendering of the view, then the processor can be a method of model parameters, and then in the process model to inside the body can be a value added.

   (5) return value is void. This is usually the result is returned directly to us in a written HttpServletResponse, if not written, then Spring will use RequestToViewNameTranslator to return a corresponding view name. If the view of the model if required, in the case of processing method returns a string of the same.

   After written to (6) If the processor annotated method @ResponseBody marked, then any type of processor, the method will return through the HttpServletResponse HttpMessageConverters conversion, rather like those in the above case as the view or model process.

   (7) In addition to the above circumstances any other type of return will be treated as a property in the model to handle, returned view or determined by The RequestToViewNameTranslator, added to the model name of the attribute can be used in the method! ModelAttribute ( "attributeName") is defined, otherwise it will use the first letter of the class name return type lowercase to represent. Use @ModelAttribute marking method will be executed before @RequestMapping marking method is executed.

4, transfer and use of data stored @ModelAttribute and @SessionAttributes

SpringMVC supports @ ModelAttribute  and @ SessionAttributes  sharing of data between different models (Model), and a controller. @ModelAttribute  mainly used in two ways, one is marked on the method, one is marked on the method parameters Controller.

When @ ModelAttribute  mark time on the method, the method will be executed before the processor performing the method, the object is returned and stored in the model or the session attributes, the attribute name may be used @ ModelAttribute ( "attributeName") method when the tag specify, if not specified, the class name (first letter lowercase) as the return type of the attribute name. About @ModelAttribute when the mark corresponding method attribute is stored in the session or stored in the model, we do an experiment, see the following section of code.

Copy the code
@Controller
@RequestMapping ( "/myTest" )
public class MyController {

    @ModelAttribute ( "hello" )
    public String getModel() {
       System. out .println( "-------------Hello---------" );
       return "world" ;
    }

    @ModelAttribute ( "intValue" )
    public int getInteger() {
       System. out .println( "-------------intValue---------------" );
       return 10;
    }

    @RequestMapping ( "sayHello" )
    public void sayHello( @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num, @ModelAttribute ( "user2" ) User user, Writer writer, HttpSession session) throws IOException {
       writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num);
       writer.write( "\r" );
       Enumeration enume = session.getAttributeNames();
       while (enume.hasMoreElements())
           writer.write(enume.nextElement() + "\r" );
    }

    @ModelAttribute ( "user2" )
    public User getUser(){
       System. out .println( "---------getUser-------------" );
       return new User(3, "user2" );
    }
}
Copy the code

When we request /myTest/sayHello.do use @ModelAttribute marking method will first perform and then they return the object stored in the model. The final visit to the sayHello method when using @ModelAttribute marking method parameters can be injected into the correct value. Execution results are as follows:

 Hello world,Hello user210

       The execution result we can see, at this time session does not include any property, that those objects are stored in the model above properties, rather than stored in the session properties. How can it be stored in a session attribute it? The first time we introduce a new concept @SessionAttributes, its use will be introduced after the finish @ModelAttribute, here we will first make use of it. We add @SessionAttributes attribute tag which is required to be stored in the session on MyController class. Look at the following code:

Copy the code
@Controller
@RequestMapping ( "/myTest" )
@SessionAttributes (value={ "intValue" , "stringValue" }, types={User. class })
public class MyController {

    @ModelAttribute ( "hello" )
    public String getModel() {
       System. out .println( "-------------Hello---------" );
       return "world" ;
    }

    @ModelAttribute ( "intValue" )
    public int getInteger() {
       System. out .println( "-------------intValue---------------" );
       return 10;
    }
   
    @RequestMapping ( "sayHello" )
    public void sayHello(Map<String, Object> map, @ModelAttribute ( "hello" ) String hello, @ModelAttribute ( "intValue" ) int num, @ModelAttribute ( "user2" ) User user, Writer writer, HttpServletRequest request) throws IOException {
       map.put( "stringValue" , "String" );
       writer.write( "Hello " + hello + " , Hello " + user.getUsername() + num);
       writer.write( "\r" );
       HttpSession session = request.getSession();
       Enumeration enume = session.getAttributeNames();
       while (enume.hasMoreElements())
           writer.write(enume.nextElement() + "\r" );
       System. out .println(session);
    }

    @ModelAttribute ( "user2" )
    public User getUser() {
       System. out .println( "---------getUser-------------" );
       return new User(3, "user2" );
    }
}
Copy the code

In the above code, we specify the property or intValue stringValue or type of city into the Session User, using the above code is accessed when we /myTest/sayHello.do following results:

 Hello world,Hello user210

Still does not print any session attribute, which is how it happened? How to define the properties of the object model and type named intValue for User objects stored in the session, but in fact it is not added to the list? Did we're wrong? We certainly are not wrong, but at the time of the first visit /myTest/sayHello.do @SessionAttributes defined need to be stored in the session attributes, but this model also has a corresponding attribute, but this time has not yet added to the session, Therefore, the session does not have any attributes, etc. after completion of the processor performing the method will add Spring model corresponding attribute in the session. So there will be the following results when requesting the second time:

 Hello world,Hello user210

user2

intValue

stringValue

When a method on a processor @ModelAttribute mark parameter indicates the value of the parameter taken from the model value of the property or the Session name, the name can be specified ( "attributeName") by @ModelAttribute, if not specified, using the class name (first letter lowercase) parameter type as the attribute name.

5, the difference between the @PathVariable and @RequestParam 

There is a variable value id on the request path, may be acquired @RequestMapping (value = "/ page / {id}", method = RequestMethod.GET) by @PathVariable  
when @RequestParam static URL request for obtaining the reference spring annotations action in use.

Summary:

handler method commonly used parameter binding annotations, we divided depending on the content part of the Request of the four categories they deal mainly on :( common type)

A, the processing requet uri  portion (referred to herein as the uri template variable, excluding queryString portion) notes: @PathVariable;

B, the processing request header annotation portion: @RequestHeader, @CookieValue;

C, the processing request body annotation portion: @RequestParam, @RequestBody;

D, the processing attribute type annotation: @SessionAttributes, @ModelAttribute;

(1), PathVariable

When using @RequestMapping URI template style mapping, i.e. someUrl / {paramId}, at this time may be bound by @Pathvariable paramId annotations on process parameter values ​​to pass over it.

Sample code:

Copy the code
@Controller  
@RequestMapping("/owners/{ownerId}")  
public class RelativePathUriTemplateController {  
  
  @RequestMapping("/pets/{petId}")  
  public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {      
    // implementation omitted   
  }  
} 
Copy the code

The code above and petId values ​​of variables ownerId the URI template, bound to the parameters of the method. If the uri template variable name and the name of the method parameters need to bind not, you need to specify the name uri template in the @PathVariable ( "name").

(2)、 @RequestHeader、@CookieValue

@RequestHeader annotations can request value Request header portion bound to the parameters of the method.

Sample code:

This is the header part of a Request:

  1. Host                    localhost:8080  
  2. Accept                  text/html,application/xhtml+xml,application/xml;q=0.9  
  3. Accept-Language         fr,en-gb;q=0.7,en;q=0.3  
  4. Accept-Encoding         gzip,deflate  
  5. Accept-Charset          ISO-8859-1,utf-8;q=0.7,*;q=0.7  
  6. Keep-Alive              300  
  1. @RequestMapping("/displayHeaderInfo.do")  
  1. public void displayHeaderInfo(@RequestHeader("Accept-Encoding") String encoding,  
  2.                               @RequestHeader("Keep-Alive") long keepAlive)  {  
  3. }  

The above code, the value of the Accept-Encoding request header portion, bound to the encoding parameters, and Keep-Alive header value is bound to the parameter keepAlive.

@CookieValue can Request header value on the cookie bound to the parameters of the method.

Cookie value, for example, the following:

  JSESSIONID=415A4AC178C59DACE0B2C9CA727CDD84

@RequestMapping("/displayHeaderInfo.do")  
public void displayHeaderInfo(@CookieValue("JSESSIONID") String cookie)  {  
} 

That is bound to the value of the parameter JSESSIONID cookie.

(3)、@RequestParam, @RequestBody

@RequestParam 

A) used to process the simple type of binding, by Request.getParameter () String obtained can be converted directly to the case of simple type (String -> a simple type of switching operation done by the configuration of the converter ConversionService); for use request.getParameter () mode acquisition parameters, it is possible to process the value of the get queryString embodiment can also handle post embodiment of the body data values ;

B) for processing Content-Type: for the  application/x-www-form-urlencodedencoded contents, submission GET, POST;

C) The annotation has two attributes: value, required; value is used to specify the value to be passed id name, required to indicate whether the parameter must be bound;

Sample code:

Copy the code
@Controller  
@RequestMapping("/pets")  
@SessionAttributes("pet")  
public class EditPetForm {  
    @RequestMapping(method = RequestMethod.GET)  
 public String setupForm(@RequestParam("petId") int petId, ModelMap model) {  
       Pet pet = this.clinic.loadPet(petId);  
   model.addAttribute("pet", pet);  
   return "petForm";  
   }
}
Copy the code

@RequestBody

The annotation process used to Content-Type: not application/x-www-form-urlencodedencoded contents, for example, application / json, application / xml like;

It is through the use of HandlerAdapter configured HttpMessageConvertersto parse post data body, and then bound to the appropriate bean.

Because equipped with FormHttpMessageConverter, so it can be used to process the  application/x-www-form-urlencodedcontent of the results processed on a MultiValueMap <String, String> where, in this case the use of some special needs, Detail View FormHttpMessageConverter api;

Sample code:

@RequestMapping(value = "/something", method = RequestMethod.PUT)  
public void handle(@RequestBody String body, Writer writer) throws IOException {  
  writer.write(body);  
} 

(4)、@SessionAttributes, @ModelAttribute

@SessionAttributes:

The annotation for the attribute value of the object HttpSession bindings, easy to use in the process parameters in.

The notes have value, types two properties, you can specify an attribute object to be used by name and type;

Sample code:

@Controller  
@RequestMapping("/editPet.do")  
@SessionAttributes("pet")  
public class EditPetForm {  
    // ...   
} 

@ModelAttribute

The annotation has two uses, a method for the one for the parameter;

When used on a method: before processing usually used @RequestMapping, model binding need, request from the background;

When the parameters used: by name to a corresponding, binds the value corresponding to the parameter name annotation bean; values ​​to be bound from:

On A) @SessionAttributes enabled attribute object;

B) @ModelAttribute model object for specified when the method;

C) above two cases are sometimes no, a new new bean objects to be bound, and the request by name in a corresponding manner to bind the values ​​to the bean.

 

@ModelAttribute sample code used in the methods of:

@ModelAttribute  
public Account addAccount(@RequestParam String number) {  
    return accountManager.findAccount(number);  
} 

The actual effect of this approach is @RequestMapping before calling the method, in order to model request an object's put ( "account", Account).

@ModelAttribute sample code used in the parameters:

@RequestMapping(value="/owners/{ownerId}/pets/{petId}/edit", method = RequestMethod.POST)  
public String processSubmit(@ModelAttribute Pet pet) {  
     
} 

The first query the Pet objects @SessionAttributes whether the binding of, if not the query on whether the method level @ModelAttribute bound Pet objects, if there is no value will be URI template in accordance with the corresponding name of the object bound to the Pet of each attribute .

 

6、< context:component-scan base-package = "" />浅析

component-scan type of annotation is the default scan @Component, however, the semantic basis @Component @Repository, @Service and @Controller also be refined after the component-scan may be obtained favor

With <context: component-scan>, another <context: annotation-config /> tag can be removed simply fall, as it has been included into the

Further <context: annotation-config /> tag also provides two sub

1. <context: include-filter> // specified scan path

2. <context: exclude-filter> // excluded from the scan path

<Context: component-scan> has a use-default-filters property, property defaults to true, indicating that all of the scans in the specified standard class packages have @Component, and is registered as the sub-bean @ @Component annotation. Service, @ Reposity and so on.

This scan granularity bit too much, if you just want to scan the specified package following Controller or other content is set use-default-filters property is false, that is no longer in accordance with the specified package scan to scan, but according to <context: include -filter> specified package scanning, examples:

<context:component-scan base-package="com.tan" use-default-filters="false">
        <context:include-filter type="regex" expression="com.tan.*"/>//注意后面要写.*
</context:component-scan>
When not provided use-default-filters attribute or attribute is true, indicates that the specified scan based on the particular route package base-packge
<context:component-scan base-package="com.tan" >
        <context:include-filter type="regex" expression=".controller.*"/>
        <context:include-filter type="regex" expression=".service.*"/>
        <context:include-filter type="regex" expression=".dao.*"/>
</context:component-scan>

 

Effect is equivalent to:
<context:component-scan base-package="com.tan" >
        <context:exclude-filter type="regex" expression=".model.*"/>
</context:component-scan>

 

Note: When I try either case <context: include-filter> and <context: exclude-filter> can not coexist

Guess you like

Origin www.cnblogs.com/gxyjava/p/12016572.html