Spring Common annotations

Source: Internet
Author: User

Using annotations to construct an IOC container

Use annotations to register beans with the spring container. Need to register in Applicationcontext.xml <context:component-scan base-package= "Pagkage1[,pagkage2,..., PagkageN]"/>

such as: Specify a package in Base-package

<!--automatically scanned-   <context:component-scan base-package = "Com.cn.hnust"/>  

Indicates that in the Com.cn.hnust package and its child packages, if a class has a specific annotation [@Component/@Repository/@Service/@Controller] on its head, the object is registered as a bean into the spring container. You can also specify multiple packages in the <context:component-scan base-package= ""/>, such as:

<context:component-scan base-package = "Com.cn.hnust,com.cn.fpc,com.cn.zl"/>

Multiple packages are separated by commas.

@Component

@Component is a common form of all spring-managed components, @Component annotations can be placed on the head of a class, @Component deprecated.

@Controller

@Controller The bean that corresponds to the presentation layer, which is the action, for example:

 PackageCom.cn.hnust.controller;ImportJavax.annotation.Resource;Importjavax.servlet.http.HttpServletRequest;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.ResponseBody;ImportCom.cn.hnust.pojo.User;ImportCom.cn.hnust.service.IUserService, @Controller @RequestMapping ("/USER")   Public classUsercontroller {@ResourcePrivateIuserservice UserService; @RequestMapping ("/showuser")//@ResponseBody    PublicString toindex (httpservletrequest request,model Model) {intUserId = Integer.parseint (Request.getparameter ("id")); User User= This. Userservice.getuserbyid (USERID); Model.addattribute ("User", user);       System.out.println (User.getpassword ()); if(User.getpassword (). Equals ("12345") ) {//return "Success" + User.getpassword ();           return"Success"; } Else {//return "fail" + User.getpassword ();       }//return "Success";        return"Fail"; }  } 

After using the @controller annotation to identify the usercontroller, it means that the usercontroller is given to the spring container, and a "usercontroller" action exists in the spring container. This name is based on the Usercontroller class name. Note: If @controller does not specify its value, the default bean name is the first lowercase of the class name for this class, if you specify value[@Controller (value= "Usercontroller")] or [@Controller ( "Useraction")], use value as the name of the bean.

You can also use @scope annotations after @Controller, such as @scope ("prototype"), to declare the scope of the action as a prototype, and you can use the container scope= "prototype" To ensure that each request has a separate action to handle, avoiding thread-safety issues with the action in struts. Spring default scope is a singleton mode (scope= "singleton"). This creates only one action object, each access is the same action object, the data is unsafe, and the struts2 requires that each access corresponds to a different action. Scope= "Prototype" ensures that an action object is created when a request is made.

@Service

The @Service corresponds to a business layer bean, for example:

 PackageCom.cn.hnust.service.impl;ImportJavax.annotation.Resource;ImportOrg.springframework.stereotype.Service;ImportCom.cn.hnust.dao.UserDao;ImportCom.cn.hnust.pojo.User;ImportCom.cn.hnust.service.IUserService; @Service ("UserService") Public classUserserviceimplImplementsIuserservice {@ResourcePrivateUserdao Userdao;  PublicUser Getuserbyid (intuserId) {        //TODO auto-generated Method Stub        return  This. Userdao.selectbyprimarykey (USERID); }    }

The @Service ("UserService") annotation is to tell spring that when spring creates an instance of Userserviceimpl, the bean's name must be called "UserService", This way, when an action requires an instance of Userserviceimpl, it is possible to create a "userservice" from spring and inject it into the action: only one name is declared "UserService" in action. Variable to receive the "UserService" injected by spring, the code is as follows:

  @Controller @RequestMapping ( "/user" )  public  class   Usercontroller {@Resource  private  iuserservice userservice; 

Note that the type of the "userservice" variable in the action declaration must be "Userserviceimpl" or its parent class "Iuserservice", otherwise it cannot be injected due to a type inconsistency because the declaration in action "UserService "Using the variable @resource annotation to annotate, this is tantamount to telling spring that I'm going to instantiate a" UserService ", you spring quickly help me instantiate, and then give me, When spring sees the annotations of the @resource on the userservice variable, it is known that the action requires an instance of Userserviceimpl, and spring will call its own created name "UserService". An instance of Userserviceimpl is injected into the "userservice" variable in the action, helping the action to complete the instantiation of the userservice so that the action is not passed through the "UserService UserService = new Userserviceimpl (); "This is the most primitive way to instantiate UserService. If there is no spring, then when the action needs to use Userserviceimpl, it must pass "userservice UserService = new Userserviceimpl ();" Actively go to create the instance object, But with spring, when the action is to use Userserviceimpl, you don't have to take the initiative to create an instance of Userserviceimpl, and the task of creating the Userserviceimpl instance is given to spring. Spring creates a good instance of Userserviceimpl and gives it to action,action to get it right. The action can be used immediately after the original active creation of the Userserviceimpl instance and becomes passive until the Userserviceimpl instance is created by spring and injected to action,action. This shows that the action on the "Userserviceimpl" class "control" has been "reversed", the original initiative in their own hands, to use the Userserviceimpl class instance, their own initiative to new one out immediately can be used, But now I can't take the initiative to go to the new "Userserviceimpl" class instance, the right of the instance of the new "Userserviceimpl" class has been taken away by spring, only spring canThe instance of the new "Userserviceimpl" class, and the action only waits for spring to create an instance of the "Userserviceimpl" class, and then "begs" spring to give him an instance of the created "Userserviceimpl" class, So that he can use "Userserviceimpl", which is spring's core idea "Control Reversal", also called"Dependency Injection"Dependency Injection" is also well understood, action needs to work with Userserviceimpl, then it is dependent on userserviceimpl, and spring injects action to the userserviceimpl that it relies on, The evil is called "Dependency injection". For action, the action relies on something, asks spring to inject it to him, and for spring, Spring takes the initiative to inject it into the action.

@Repository

@Respository the corresponding database access layer bean, for example:

 Package Com.cn.hnust.dao; Import Org.apache.ibatis.annotations.Select; Import org.springframework.stereotype.Repository; Import Com.cn.hnust.pojo.User; @Repository  Public Interface Userdao {//    @Select ("select * from user_t where Id=#{userid}")     public User selectbyprimarykey (int  userId);}

@Repository note tells Spring to let spring create a user named "Userdao".

Userdao instances, you can use @resource annotations to tell spring when a service needs to use a Userdao instance of the name "Userdao" created by spring. Spring injects the created Userdao to the service:

 PackageCom.cn.hnust.service.impl;ImportJavax.annotation.Resource;ImportOrg.springframework.stereotype.Service;ImportCom.cn.hnust.dao.UserDao;ImportCom.cn.hnust.pojo.User;ImportCom.cn.hnust.service.IUserService; @Service ("UserService") Public classUserserviceimplImplementsIuserservice {@ResourcePrivateUserdao Userdao;  PublicUser Getuserbyid (intuserId) {        //TODO auto-generated Method Stub        return  This. Userdao.selectbyprimarykey (USERID); }    }

Spring Common annotations

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.