Introduction to common annotations in spring

Source: Internet
Author: User
Tags aop class definition

How the configuration file is written when using annotations in spring:
  <?xml version= "1.0" encoding= "UTF-8"?> <span style= "FONT-SIZE:18PX;" ><beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:xsi= "http://www.w3.org/2001/ Xmlschema-instance "xmlns:context=" Http://www.springframework.org/schema/context "xmlns:aop=" HTTP://WWW.SPRINGF Ramework.org/schema/aop "xsi:schemalocation=" Http://www.springframework.org/schema/beans http://www.springframe Work.org/schema/beans/spring-beans-3.0.xsd Http://www.springframework.org/schema/context/HTTP Www.springframework.org/schema/context/spring-context-3.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP/HTTP Www.springframework.org/schema/aop/spring-aop-3.0.xsd Http://www.springframework.org/schema/util/HTTP Www.springframework.org/schema/util/spring-util-3.0.xsd "> <aop:aspectj-autoproxy/> <context:annota tion-config/> <context:component-scan base-package= "com.test"/> </beans>  
Configuration items are configured to scan the specified packages for dependency injection.
- @Controller- @Service- @Autowired- @RequestMapping- @RequestParam- @ModelAttribute- @Cacheable- @CacheFlush- @Resource- @PostConstruct- @PreDestroy- @Repository- @Component (不推荐使用)- @Scope- @SessionAttributes- @InitBinder- @Required- @Qualifier
The following are some common annotations that are used:
@Autowired  private IReportService reportService ;  
@Autowired

Spring2.5 introduces @Autowired annotations that allow you to annotate class member variables, methods, and constructors to accomplish the task of automating Assembly. In addition, the @Autowired Get,set method can be eliminated. @Autowiredis automatically transferred according to the type.
It is important to note that @Resource automatic assembly is also possible, but @Resource by default it is automatically assembled by name.

@Autowired look up from the spring line based on the bean type, the registration type must be unique, otherwise the exception will be reported. The difference from @Resource is that @Resource allow lookups by bean name or bean type @Autowired (required=false), if the type's bean is not found in the spring context, will use new Softpmserviceimpl ();

When a @Autowired callout acts on a map type, if the map's key is of type String, Spring adds the bean that has the type of value corresponding to map in the container, using the bean's ID or name as the The key of the MAP.

@Autowired Another function is to label it in the Beanfactory type, ApplicationContext type, Resourceloader type, applicationeventpublisher type, Messagesource type, Spring automatically injects instances of these implementation classes without the need for additional action.

Here is a brief description of what is assembled by type and what is assembled by name?

By type, this property is automatically assembled if there is a bean in the spring container that is the same as the specified attribute type, and if there are more than one bean of that type, the exception is run and the automatic assembly by type is not available, and if no matching bean is found, Then nothing happens.
The so-called automatic assembly by name, which is based on the name of the property, examines the bean in the spring container that exactly matches the attribute name, and is automatically assembled.

@Qualifier

When using a @Autowired, if more than one bean of the same type is found, an exception is thrown, which can be injected using the @Qualifier ("Beanname"), which explicitly specifies the name of the Bean, which is the same as @Resource specifying the Name property.

@Component
@Component("reportAction")  @Scope("request")  public class ReportAction extends AbstractBaseAction  
The following explanations are from the official documentation

@Repository, @Service and @Controller .
@Componentis a common form of all the spring management components;
and @Repository , @Service and, @Controller @Component refinement, used to represent more specific use cases (for example, the persistence layer, the service layer, and the presentation layer, respectively). In other words, you can @Component annotate your component classes,
But if @Repository you use, @Service or @Controller annotate them, your class might be better handled by tools or associated with facets.
For example, these typical annotations can be ideal pointcut targets. Of course, in later versions of the Spring framework @Repository , @Service and @Controller Perhaps more semantics can be carried. As a result, if you are considering whether the service layer is @Component to be used or not @Service ,
That @Service 's obviously a better choice. Again, as previously stated, it @Repository has been used as a marker for exception conversions in the persistence layer.

@Controller
<!--方式一--在SpringMVC 的配置文件中定义MyController 的bean 对象--><bean class="com.host.app.web.controller.MyController"/><!--方式二--在SpringMVC 的配置文件中告诉Spring 该到哪里去找标记为@Controller 的Controller 控制器。-->< context:component-scan base-package = "com.host.app.web" />//路径写到controller的上一层

In SPRINGMVC, controller controllers are responsible for processing requests distributed by Dispatcherservlet, which encapsulates the data requested by the user into a model after processing it through the business processing layer, and then returns the model to the corresponding view for presentation. A very simple way to define a controller is provided in SPRINGMVC, where you do not need to inherit a particular class or implement a specific interface, just use the @Controller tag a class is a controller, and then use @RequestMapping and @ Some annotations, such as Requestparam, define the mapping between the URL request and the Controller method, so that the controller can be accessed by the outside world. In addition, the controller does not directly depend on HttpServlet objects such as HttpServletRequest and HttpServletResponse, which can be obtained flexibly through the controller's method parameters.

@Service
@Servicepublic class SoftCreateServiceImpl implements ISoftCreateService {}//或者@Service("softCreateServiceImpl")

@Service is responsible for registering a bean into the spring context, the bean ID defaults to the class name beginning with the lowercase letter

@Repository

Similar to @Controller, @Service, the Bean is registered with the spring context.

@Resource
@Resourceprivate DataSource dataSource; // inject the bean named 'dataSource'@Resource(name="dataSource")@Resource(type=DataSource.class)

@Resource is found by default by the Bean's name, and if no find is done by type, it is similar to @Autowired.
If you do not explicitly specify the Name property for a @Resource annotation, label it in the Beanfactory type, ApplicationContext type, Resourceloader type, Applicationeventpublisher type, 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;

@RequestMapping
@Controller @RequestMapping("/bbtForum.do")public class BbtForumController {    @RequestMapping(params = "method=listBoardTopic")    public String listBoardTopic(int topicId,User user) {}}@RequestMapping("/softpg/downSoftPg.do")@RequestMapping(value="/softpg/ajaxLoadSoftId.do", method=RequestMethod.POST)@RequestMapping(value="/osu/product/detail.do", params={"modify=false"}, method=RequestMethod.POST)

@RequestMapping can be declared on a class or method

Parameter binding description
If we use the following URL request:

http://localhost/bbtForum.do?method=listBoardTopic&topicId=1&userId=10&userName=tom

The 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 point the User.userid value is 0. If the user object has a Dept.deptid cascading property, it binds to the Dept.deptid URL parameter.

The requestmapping annotation has six properties, and we'll describe her in three categories below (there are examples below).
1、 value, method;value:指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);method:指定请求的method类型,GET、POST、PUT、DELETE等;2、consumes,producesconsumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;produces:    指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;3、params,headersparams: 指定request中必须包含某些参数值是,才让该方法处理。headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。
@RequestParam
@RequestParam("id")@RequestParam(required=false) //参数不是必须的,默认为true@RequestParam(value="id",required=false)
http://localhost/bbtForum.do?method=listBoardTopic&id=1&userId=10&userName=tom

Listboardtopic (@RequestParam ("id") int topicid,user user) TopicID bind to the URL parameter of the ID, then you can use @RequestParam annotations for the entry to achieve the purpose

@Scope
@Scope("session")@Repository()public class UserSessionBean implementsSerializable {}

When you use XML to define beans, you can define the scope of a bean through the bean's scope property, which can also be done by @scope annotations.

The following values can be specified in the @Scope:

    • Singleton: Defines a bean's scope as an instance of each spring container (default value)
    • Prototype: the definition bean can be instantiated multiple times (use once to create one time)
    • Request: Defining the scope of the bean is an HTTP request (valid in SPRINGMVC)
    • Session: Defines the scope of the bean to be an HTTP session (valid in SPRINGMVC)
    • Global-session: Defines the scope of the bean as a global HTTP session (valid in the Portlet)
@SessionAttributes
@SessionAttributes("currUser") // 将ModelMap 中属性名为currUser 的属性@SessionAttributes({"attr1","attr2"})@SessionAttributes(types = User.class)@SessionAttributes(types = {User.class,Dept.class})@SessionAttributes(types = {User.class,Dept.class},value={"attr1","attr2"})

Spring allows us to selectively specify which attributes in the modelmap need to be dumped into the session,
These properties can also be accessed in the list of properties for the next request that belongs to the corresponding modelmap.
This function is implemented by annotating @SessionAttributes annotations at the class definition.
@SessionAttributes can only be declared on a class, not on a method.

@Controller  @RequestMapping("/bbtForum.do")  @SessionAttributes("currUser") //@1将ModelMap中属性名为currUser的属性  //放到Session属性列表中,以便这个属性可以跨请求访问</span>  public class BbtForumController {  …      @RequestMapping(params = "method=listBoardTopic")      public String listBoardTopic(@RequestParam("id")int topicId, User user,  ModelMap model) {          bbtForumService.getBoardTopics(topicId);          model.addAttribute("currUser",user);//@2向ModelMap中添加一个属性</span>          return "listTopic";      }    }  

We added a Modelmap property to the @2 where the property name is Curruser, and @1 places the Modelmap property named Curruser in the Session by @SessionAttributes annotation, so we can not only Stboardtopic () Request the JSP view page for the user object through Request.getattribute ("Curruser") and Session.getattribute ("Curruser"). You can also access this property through Session.getattribute ("Curruser") or Modelmap#get ("Curruser") in the JSP view page for the next request.

@ModelAttribute
@Controller  @SessionAttributes("currentUser")public class GreetingController{      @RequestMapping      public void hello(@ModelAttribute("currentUser") User user){        //user.sayHello()      }  }

We can add a @SessionAttributes to the controller that needs to access the session property, and then add @ModelAttribute on the user parameter that the action requires, and ensure that the property names are the same. SPRINGMVC will automatically inject @SessionAttributes-defined attributes into the Modelmap object, and in the Setup Action's argument list, go to Modelmap to get such objects and add them to the parameter list. As long as we do not call Sessionstatus's SetComplete () method, this object will remain in the session, thus realizing the sharing of session information.

@Required
@Required              public setName (String name) {}

The @Required is responsible for checking that 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.

@PostConstruct

With annotations @PostConstruct on 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

Adding annotations to the method @PreDestroy, this method is executed by the spring container before the bean is destroyed.

@PathVariable
@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";       }  }

Used to map the template variables in the request URL to the parameters of a feature processing method, that is, the variables in the URI template are taken as parameters.

Introduction to common annotations in spring

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.