Description of Spring Annotations Spring2.5 annotations (3.0 general)

Source: Internet
Author: User
Tags class definition dateformat http post locale

Spring Note Description Spring2.5 Note Introduction (3.0 General) Register Note processor

Way One: Bean
<bean class= "Org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/>
Way Two: namespaces
<context:annotation-config/><context:annotationconfig/>
The spring container is implicitly registered with the Autowiredannotationbeanpostprocessor, Commonannotationbeanpostprocessor,
Persistenceannotationbeanpostprocessor and Requiredannotationbeanpostprocessor the 4 beanpostprocessor.
Way Three: namespaces
<context:component-scan/>
If you want to make annotations work, you must configure Component-scan, and you do not actually need to configure Annotation-config. The Base-package property specifies the class package that needs to be scanned.
All classes in the class package and its recursive child packages are processed. Also allows defining filters to include or exclude certain classes under the base package.

Spring supports the following 4 types of filtering methods

1) Note org.example.SomeAnnotation to filter all classes that use someannotation annotations
2) class name designation: Org.example.SomeClass Filter the specified class
3) Regular expression: Com.kedacom.spring.annotation.web. * Filter Some classes with regular expressions
4) AspectJ: Expression org.example. *service+ filtering some classes by ASPECTJ expressions


Examples of how regular expressions are filtered:

<context:component-scanbase-package= "Com.casheen.spring.annotation" >
<context:exclude-filtertype= "regex" expression= "com.casheen.spring.annotation.web. * "/>
</context:component-scan>

Examples of how annotations are filtered:

<context:component-scan base-package= "Com.netqin" >
<context:include-filter type= "Annotation" expression= "Org.springframework.stereotype.Controller"/>
<context:include-filter type= "Annotation" expression= "Org.springframework.stereotype.Service"/>
<context:include-filter type= "Annotation" expression= "Org.springframework.stereotype.Repository"/>
</context:component-scan>

Enable Spring MVC annotations

Start the Spring MVC Annotation feature to complete the mapping of requests and annotations Pojo

<bean class= "Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/>

optional type of the request processing method return value
voidThe logical view name is determined by the URL that corresponds to the request processing method, such as the following method: @RequestMapping ("/welcome.do")             Public voidWelcomehandler () {} corresponds to a logical view named' Welcome 'String At this point the logical view is named as the returned character, as in the following methods: @RequestMapping ( method=requestmethod.get) PublicString Setupform (@RequestParam ("ownerID")intownerID, Modelmap model) {Owner owner= This. Clinic.loadowner (ownerID);                Model.addattribute (owner); return"Ownerform";            The logical view name is the same as "Ownerform" Org.springframework.ui.ModelMap and the return type is void, depending on the URL of the corresponding request, as in the following example: @RequestMapping ("/vets.do")             PublicModelmap Vetshandler () {return NewModelmap ( This. Clinic.getvets ()); The corresponding logical view is named' Vets ', the returned MODELMAP will be the model object corresponding to the request, which can be accessed in the JSP view page. Modelandview, of course, can also be a traditional modelandview.

@Controller
For example @Controller  Public class extends Simplebasecontroller {} or @Controller ("Softcreatecontroller") Description @Controller is responsible for registering a bean into the spring context, B EAN ID defaults to class name start letter lowercase
@Service
for    example    @Service  publicclassimplements  Isoftcreateservice {} or    @ Service ("Softcreateserviceimpl") Description    @Service is responsible for registering a bean into the spring context, the bean ID defaults to the class name beginning with the lowercase letter
@Autowired
For example @AutowiredPrivateIsoftpmservice Softpmservice; or @Autowired (required=false)        PrivateIsoftpmservice Softpmservice =NewSoftpmserviceimpl ();        Description @Autowired Lookup from the spring context based on the bean type, the registration type must be unique, or the exception will be reported. The difference with @resource is that the @Resource allows you to find @autowired either by bean name or bean type (required=false) indicated. If a bean of that type is not found in the spring context, new Softpmserviceimpl () is used, and when the @Autowired callout is applied to the map type, if map's key is of type string, spring will        The type of bean that corresponds to the type of map value is added, with the Bean's ID or name as the map key. @Autowired Another function is to label it in Beanfactory, ApplicationContext, Resourceloader, Applicationeventpublisher, Messagesource type, spring automatically injects instances of these implementation classes without the need for additional action. 
@RequestMapping
class Annotations @Controller @RequestMapping ("/bbtforum.do")         Public classBbtforumcontroller {@RequestMapping (params= "Method=listboardtopic")             PublicString Listboardtopic (intTopicid,user User) {}} Method annotation @RequestMapping ("/softpg/downsoftpg.do") @RequestMapping (value= "/softpg/ajaxloadsoftid.do", method =POST) @RequestMapping (value= "/osu/product/detail.do", params = {"Modify=false"}, Method =POST) Description @RequestMapping can be declared to a class or method on a parameter binding description if we use the following URL Request: Example: http://Localhost/bbtforum.domethod=listboardtopic&topicid=1&userid=10&username=tomThe topicid URL parameter is bound to the TopicID import parameter, and the UserID and userName URL parameters are bound to the UserID and UserName properties of the user object. and URL requests are not allowed without the TopicID parameter, although the user's UserID property type is the basic data type, but if the UserID parameter does not exist in the URL, spring will not error, at this time User.user The ID value is0. If the user object has a Dept.deptid cascading property, it binds to the Dept.deptid URL parameter.
@RequestParam
parameter Binding description @RequestParam ("id") http://Localhost/bbtforum.domethod=listboardtopic&id=1&userid=10&username=tomListboardtopic (@RequestParam ("id")inttopicid,user User) TopicID binding to the ID of this URL parameter, you can use @RequestParam annotations to the entry to achieve the purpose @RequestParam (required=false): The parameter is not required, and the default is True @RequestParam (value= "id", required=falsethe optional type of Java base data type and String by default for the request processing method to bind to the URL parameter by name, you can change the default binding rule by @RequestParam annotations request/response/The session can be either a servlet API or an object corresponding to the Portlet API, and spring binds them to the corresponding objects on the servlet and Portlet containers Org.springframework.web.con The text.request.WebRequest interior contains the request object Java.util.Locale bound to the locale object corresponding to the request Java.io.InputStream/Java.io.Reader can take this access to the content of the request Java.io.OutputStream/Java.io.Writer can take this action response the contents of any labeled @RequestParam annotations into arguments bound to a specific request parameter. Java.util.Map/Org.springframework.ui.ModelMap It binds the potential model objects created by each request in the Spring MVC framework, which can be accessed by Web view objects (such as SP) commands/Form Object (Note: The object that binds a URL parameter sent using HTTP GET is generally called a command object, whereas an object that binds a URL parameter sent using an HTTP POST is a Form object) their properties are bound to the URL parameter with a rule that matches the name, and the conversion of the type is done. The rules for type conversions can be adjusted by @InitBinder annotations or by Handleradapter configuration org.springframework.validation.Errors/org.springframework.validation.bindingresult the check result for the command/form object in the attribute list, note that the test result parameter must follow the command/after the form object Org.springframework.web.bind.support.SessionStatus can explicitly end the processing of the form through the type status object, which is equivalent to triggering Session clears the properties defined by @sessionattributes
@ModelAttribute
Scope : Request    For example        @RequestMapping ("/base/usermanagecooper/init.do")        public String Handleinit (@ModelAttribute ("Querybean") manageduser Suser,model Model,) {    or        @ModelAttribute ( "Coopmap")//  return coopmap to page public         map<long,cooperatorinfo>  Coopmapitems () {}    description        @ModelAttribute declared on the property, indicating that the value of the property is derived from "Querybean" in the model, and is saved in the model @modelattribute declaration on the method, indicating that the return value of the method is saved in the model
@Cacheable and @cacheflush
@Cacheable: Declares that the return value of a method should be cached. For example: @Cacheable (modelid = "Testcaching" = "testcaching")    description        to be used with the cache processor, refer to: http:// hanqunfeng.iteye.com/blog/603719        SPRING3.0 does not support caching, but after 3.1 it is available for reference: Spring3.1 cache annotations
@Resource
    for        example        @Resourceprivate//  inject the bean named ' DataSource '     or        @Resource (name= "DataSource")        @Resource (Type=datasource.  Class)    description        @Resource Find by the bean's name by default, and if not found, it will be searched by type, which is similar to @autowired. In the absence of an explicit designation for @Resource annotations Name attribute,        if it is labeled in Beanfactory, ApplicationContext, Resourceloader, Applicationeventpublisher, Messagesource type,        spring automatically injects instances of these implementation classes without the need for additional action. The Name property does not need to be specified (or specified as "") at this time , otherwise the injection fails.
@PostConstruct
    By adding annotation @postconstruct to the method, this method is executed by the spring container after the bean is initialized (note: Bean initialization includes, instantiates the bean, and assembles the Bean's attributes (Dependency injection)).    @PreDestroy        Add annotation @predestroy to the method, this method is executed by the spring container before the bean is destroyed.    @Repository,         like @controller, @Service, are registering beans with the spring context and not repeating them.
@Component (deprecated)
    @Component is a common form of all of the spring management components, spring also provides a more granular form of annotations:     @Repository, @Service, @Controller they correspond to storage-tier beans, The business layer bean, and the presentation layer bean.    Versions (2.5), these annotations are the same as the semantics of @component and are completely generic, and may add more semantics to them in later versions of spring.    Therefore, we recommend the use of @repository, @Service, @Controller to replace @component. 
@Scope
    For example    @Scope ("Session")    @Repository    publicclass  Usersessionbean implementsserializable {}    shows that        when you use XML to define beans, you can define the scope of a bean through the bean's scope property. The same can be done with @scope annotations, where the following values can be specified @Scope:            singleton: Defines the bean's scope as an instance of each spring container (the default)            prototype: The definition bean can be instantiated multiple times ( Create once using once)            request: Defines the scope of the bean to be an HTTP request (valid in SPRINGMVC)            session: Defines the scope of the bean is the HTTP session (valid in SPRINGMVC)            Global -session: Defines the scope of the bean as a global HTTP session (valid in the Portlet)
@SessionAttributes
Note that spring allows us to selectively specify which properties in the Modelmap need to be dumped into the session so that the next request belongs to the corresponding Modelmap property list, which is also accessible to those properties.        This function is implemented by annotating @SessionAttributes annotations at the class definition.    @SessionAttributes can only be declared on a class, not on a method. For example @SessionAttributes ("Curruser")//Save the attribute named Curruser in Modelmap to the session@SessionAttributes ({"Attr1", "ATTR2"}) @SessionAttributes (Types= User.class) @SessionAttributes (Types= {User.class, Dept.class}) @SessionAttributes (Types= {User.class, Dept.class},value={"Attr1", "ATTR2"}) @InitBinder description if you want a property editor to work only with a specific controller, you can define a callout @InitBinder annotation in the controller and you can register it with the controller in that method. A number of property editors such as @InitBinder Public voidInitbinder (Webdatabinder binder) {SimpleDateFormat DateFormat=NewSimpleDateFormat ("Yyyy-mm-dd"); Dateformat.setlenient (false); Binder.registercustomeditor (Date.class,NewCustomdateeditor (DateFormat,false)); }
@Required
    for        example                      @requiredpublic  setName (String name) {}     Description        @ Required is responsible for checking whether a bean's declared set method is executed when it is initialized, and when a setter method that is labeled @required is not called,        Spring throws an exception when parsing, reminding the developer to set the corresponding property. @Required annotations can only be labeled on the setter method.        because the nature of dependency injection is to check that the setter method is called, instead of actually checking to see if the property is assigned a value and what value is assigned.        If the annotation is marked in a non-setxxxx () type method, it is ignored. 
@Qualifier
    For example        @Autowired        @Qualifier ("Softservice")        private  Isoftpmservice Softpmservice;        when using @autowired, if you find more than one bean of the same type, you throw an exception, you can use the @Qualifier ("Beanname") to explicitly specify the name of the bean to inject        at this time with @ resource specifies that the Name property has the same effect. 

Description of Spring Annotations Spring2.5 annotations (3.0 general)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.