Spring MVC常用注解

合集下载

requestparam参数

requestparam参数

requestparam参数
RequestParam参数是SpringMVC框架中常用的注解之一,它可以用来获取请求参数的值。

RequestParam注解可以添加到方法的参数上,用于指定该参数对应的请求参数名称。

例如,
@RequestParam('userId') String userId,表示获取名为'userId'的请求参数值并赋值给userId变量。

RequestParam注解有以下一些属性:
1. value,用于指定请求参数名称,如果不指定,则默认使用方法参数名称作为请求参数名称。

2. required,用于指定该参数是否必须传递,默认为true。

3. defaultValue,用于指定请求参数的默认值,如果该参数没有传递,则使用默认值。

注意:使用RequestParam注解时,请求参数的名称和方法参数的名称要保持一致,否则会出现获取不到参数值的情况。

RequestParam注解还支持将多个参数值封装为一个集合或数组类型的参数,例如:
1. @RequestParam('ids') List<Integer> ids,表示获取名为'ids'的多个请求参数值并封装为Integer类型的List集合。

2. @RequestParam('names') String[] names,表示获取名为'names'的多个请求参数值并封装为String类型的数组。

除了RequestParam注解,Spring MVC还提供了其他类似的注解,如PathVariable、RequestBody等,可以根据具体情况选择使用。

requestbody注解

requestbody注解

requestbody注解requestbody注解可以说是SpringMVC中的一个重要的注解,它可以用来处理HTTP请求中的实体数据,在处理请求数据时,可以使用SpringMVC框架来处理用户发来的实体数据,而requestbody注解就是SpringMVC中处理实体数据的一种最常用的方式。

首先,我们来看看什么是requestbody注解,它是SpringMVC中的一种注解,它的主要作用是用来处理客户端发来的实体数据,也就是处理HTTP请求中的实体数据。

它可以用来将实体数据通过网络传输到服务器端,并将服务器端接收到的实体数据转换成业务对象。

其次,我们来了解requestbody注解的具体用法。

requestbody 注解可以用来接收客户端HTTP请求,它还可以用来将实体数据转换成业务对象,也就是将实体数据映射成映射实体。

此外,它还可以用来接收多种类型的数据,比如XML、JSON等等。

现在,让我们来看看如何在SpringMVC中使用requestbody注解。

在使用requestbody注解的时候,首先你要在客户端发出的HTTP请求中添加@requestbody注解,这样,HTTP请求中的实体数据就可以以requestbody的形式被SpringMVC框架接收。

接着,你就可以使用@requestbody注解标记在方法参数上,以将实体数据转换为映射实体,例如:@RequestMapping(/user/addpublic void addUser(@RequestBody User user){userService.addUser(user);}最后,requestbody注解还可以用来接收多种格式的数据,例如XML、JSON等等,只要将@RequestBody注解标记在方法参数上,就可以在HTTP请求中接收不同格式的实体数据。

到此,requestbody注解的使用方法就介绍完了,requestbody 注解可以说是SpringMVC中的一个重要的注解,它的出现使得处理客户端发送的实体数据变得更加方便。

详解SpringMVC注解@initbinder解决类型转换问题

详解SpringMVC注解@initbinder解决类型转换问题

详解SpringMVC注解@initbinder解决类型转换问题在使⽤SpringMVC的时候,经常会遇到表单中的⽇期字符串和JavaBean的Date类型的转换,⽽SpringMVC默认不⽀持这个格式的转换,所以需要⼿动配置,⾃定义数据的绑定才能解决这个问题。

在需要⽇期转换的Controller中使⽤SpringMVC的注解@initbinder和Spring⾃带的WebDateBinder类来操作。

WebDataBinder是⽤来绑定请求参数到指定的属性编辑器.由于前台传到controller⾥的值是String类型的,当往Model⾥Set这个值的时候,如果set的这个属性是个对象,Spring就会去找到对应的editor进⾏转换,然后再SET进去。

代码如下:@InitBinderpublic void initBinder(WebDataBinder binder) {SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");dateFormat.setLenient(false);binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));}需要在SpringMVC的配置⽂件加上<!-- 解析器注册 --><bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"><property name="messageConverters"><list><ref bean="stringHttpMessageConverter"/></list></property></bean><!-- String类型解析器,允许直接返回String类型的消息 --><bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter"/>换种写法<mvc:annotation-driven><mvc:message-converters><bean class="org.springframework.http.converter.StringHttpMessageConverter"><constructor-arg value="UTF-8"/></bean></mvc:message-converters></mvc:annotation-driven>拓展:spring mvc在绑定表单之前,都会先注册这些编辑器,Spring⾃⼰提供了⼤量的实现类,诸如CustomDateEditor,CustomBooleanEditor,CustomNumberEditor等许多,基本上够⽤。

什么是SpringMVC?

什么是SpringMVC?

什么是SpringMVC?⼀、什么是SpringMVC?1.SpringMVC 是⼀种基于 Java 的实现 MVC 设计模型的请求驱动类型的轻量级 Web 框架,属于SpringFrameWork的后续产品,已经融合在Spring Web Flow 中。

2.SpringMVC = Spring +MVCspring mvc类似于struts的⼀个MVC开框架,其实都是属于spring,spring mvc需要有spring的架包作为⽀撑才能跑起来.spring是⼀个⼀站式的框架,提供了表现层(springmvc)到业务层(spring)再到数据层(springdata)的全套解决⽅案;spring的两⼤核⼼IOC(控制反转)和AOP(⾯向切⾯编程)更是给我们的程序解耦和代码的简介提供了⽀持。

Spring框架图:从Spring的结构图可以看出,springMVC位于spring web端的⼀个框架,是⼀种基于Java的实现了Web MVC设计模式的请求驱动类型的轻量级Web框架,即使⽤了MVC架构模式的思想,将web层进⾏职责解耦。

附:基于请求驱动指的就是使⽤请求-响应模型。

从名字上就可以窥探出,Spring>SpringMVC,那么事实上,spring和SpringMVC是⼀种⽗⼦关系。

SpringMVC是spring扩展出的⼀个应⽤于web端的框架。

在这⾥需要注意的⼀点,就是到底什么是⽗⼦容器关系:spring主要的作⽤是黏合其他模块组件,进⾏统⼀管理,springmvc则主要是负责web端。

那么,我们都知道,我们在应⽤spring的时候,可以使⽤注⼊。

这个时候,如果我们的web端是⽤的SpringMVC,这个时候,controller理论上是通过SpringMVC去注⼊,但是,使⽤spring注⼊,同样是可⾏的。

同理,service等层,使⽤SpringMVC配置的统⼀扫描装配也是可以的。

框架的常用注解

框架的常用注解

框架的常用注解在软件开发中,框架是一种重要的工具,它可以帮助我们快速构建应用程序,并提供一些常见功能的实现。

而在使用框架的过程中,注解是一种非常常见的工具,它可以帮助我们更好地使用框架的功能。

下面将介绍一些常用的框架注解。

1.@Autowired:这是Spring框架中常用的注解之一。

它可以自动装配一个bean对象,简化了我们在配置文件中手动配置bean的步骤。

通过使用@Autowired注解,我们可以直接在类中使用需要的bean对象,而无需关心具体的实现和配置细节。

2.@RequestMapping:这是Spring MVC框架中常用的注解之一。

它可以将HTTP请求映射到相应的处理方法上。

通过使用@RequestMapping注解,我们可以指定URL和处理方法之间的映射关系,使得请求能够被正确地路由到相应的处理方法中。

3.@Entity:这是Hibernate框架中常用的注解之一。

它用于标识一个Java类是一个持久化类,即将该类的对象映射到数据库的表中。

通过使用@Entity注解,我们可以简化我们在配置文件中手动配置持久化类和数据库表之间的映射关系的步骤。

4.@Transactional:这是Spring框架中常用的注解之一。

它可以将一个方法标记为事务处理方法。

通过使用@Transactional注解,我们可以在方法内部进行数据库操作,并自动管理事务的提交和回滚。

这样可以简化我们在代码中手动管理事务的步骤,提高代码的可维护性和可读性。

5.@PathVariable:这是Spring MVC框架中常用的注解之一。

它可以将URL中的参数绑定到方法的参数上。

通过使用@PathVariable 注解,我们可以获取到URL中的路径参数,并将其传递给方法进行处理。

这样可以方便地获取到用户传递的参数,进一步完善程序的功能。

总结起来,注解是一种非常方便和实用的工具,在框架的开发和使用中发挥着重要的作用。

通过使用框架提供的常用注解,我们可以简化配置和实现的步骤,提高开发效率,同时也使得代码更加易读和可维护。

springmvc对参数接收的两个注解@RequestParam和@RequestBody

springmvc对参数接收的两个注解@RequestParam和@RequestBody

springmvc对参数接收的两个注解@RequestParam和
@RequestBody
@RequestParam
作⽤:将请求参数绑定到控制器的⽅法参数上,主要⽤于接收⼏班类型参数
语法:@RequestParam(value=”参数名”,required=”true/false”,defaultValue=””)
value:参数名
required:是否包含该参数,默认为true,表⽰该请求路径中必须包含该参数,如果不包含就报错。

defaultValue:默认参数值,如果设置了该值,required=true将失效,⾃动为false,如果没有传该参数,就使⽤默认值
@RequestBody
@RequestBody主要⽤来接收前端传递给后端的json字符串中的数据的(请求体中的数据的);GET⽅式⽆请求体,所以使⽤@RequestBody 接收数据时,前端不能使⽤GET⽅式提交数据,⽽是⽤POST⽅式进⾏提交。

在后端的同⼀个接收⽅法⾥,@RequestBody与
@RequestParam()可以同时使⽤,@RequestBody最多只能有⼀个,⽽@RequestParam()可以有多个。

1.1SpringBoot环境配置和常用注解

1.1SpringBoot环境配置和常⽤注解Spring Boot常⽤注解:@Service: 注解在类上,表⽰这是⼀个业务层bean@Controller:注解在类上,表⽰这是⼀个控制层bean@Repository: 注解在类上,表⽰这是⼀个数据访问层bean@Component:注解在类上,表⽰通⽤bean ,value不写默认就是类名⾸字母⼩写@Autowired:按类型注⼊.默认属性required= true;当不能确定Spring 容器中⼀定拥有某个类的Bean 时,可以在需要⾃动注⼊该类Bean 的地⽅可以使⽤@Autowired(required = false),这等于告诉Spring:在找不到匹配Bean时也不抛出BeanCreationException 异常。

@Autowired 和 @Qualifier 结合使⽤时,⾃动注⼊的策略就从byType 转变byName 了。

@Autowired可以对成员变量、⽅法以及构造函数进⾏注释,⽽@Qualifier 的标注对象是成员变量、⽅法⼊参、构造函数⼊参。

正是由于注释对象的不同,所以 Spring 不将 @Autowired 和 @Qualifier 统⼀成⼀个注释类。

@Resource:按名称装配区别:@Resource默认按照名称⽅式进⾏bean匹配,@Autowired默认按照类型⽅式进⾏bean匹配@Resource(importjavax.annotation.Resource;)是J2EE的注解,@Autowired(importorg.springframework.beans.factory.annotation.Autowired;)是Spring的注解@Configuration:注解在类上,表⽰这是⼀个IOC容器,相当于spring的配置⽂件,java配置的⽅式。

IOC容器的配置类⼀般与@Bean 注解配合使⽤,⽤@Configuration 注解类等价与 XML 中配置 beans,⽤@Bean 注解⽅法等价于 XML 中配置 bean。

SpringMVC中post请求参数注解@requestBody使用问题

SpringMVC中post请求参数注解@requestBody使⽤问题⼀、httpClient发送Post1public static String httpPostWithJSON(String url) throws Exception {23 HttpPost httpPost = new HttpPost(url);4 CloseableHttpClient client = HttpClients.createDefault();5 String respContent = null;67// json⽅式8 JSONObject jsonParam = new JSONObject();9 jsonParam.put("name", "admin");10 jsonParam.put("pass", "123456");11 StringEntity entity = new StringEntity(jsonParam.toString(),"utf-8");//解决中⽂乱码问题12 entity.setContentEncoding("UTF-8");13 entity.setContentType("application/json");14 httpPost.setEntity(entity);15 System.out.println();161718// 表单⽅式19// List<BasicNameValuePair> pairList = new ArrayList<BasicNameValuePair>();20// pairList.add(new BasicNameValuePair("name", "admin"));21// pairList.add(new BasicNameValuePair("pass", "123456"));22// httpPost.setEntity(new UrlEncodedFormEntity(pairList, "utf-8")); //UrlEncodedFormEntity默认"application/x-www-form-urlencoded"232425 HttpResponse resp = client.execute(httpPost);26if(resp.getStatusLine().getStatusCode() == 200) {27 HttpEntity he = resp.getEntity();28 respContent = EntityUtils.toString(he,"UTF-8");29 }30return respContent;31 }323334public static void main(String[] args) throws Exception {35 String result = httpPostWithJSON("http://localhost:8080/hcTest2/Hc");36 System.out.println(result);37 }封装表单属性可以⽤json也可以⽤传统的表单,如果是传统表单的话要注意,也就是在上边代码注释那部分。

spring mvc注解实例

本文主要介绍使用注解方式配置的spring mvc,包括数据访问层的实现web.xml配置:<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="/2001/XMLSchema-instance" xmlns="http:// /xml/ns/javaee" xmlns:web="/xml/ns/javaee/web-ap p_2_5.xsd" xsi:schemaLocation="/xml/ns/javaee http://java.su /xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"><display-name>s3h3</display-name><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext*.xml</param-value></context-param><listener><listener-class>org.springframework.web.context.ContextLoaderListener</l istener-class></listener><servlet><servlet-name>spring</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servle t-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring</servlet-name> <!-- 这里在配成spring,下边也要写一个名为spring-servlet.xml的文件,主要用来配置它的controller --><url-pattern>*.do</url-pattern></servlet-mapping><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list></web-app>spring-servlet,主要配置controller的信息<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:xsi="/2001/XMLSchema-instance" xmlns:p="http:// /schema/p"xmlns:context="/schema/context"xsi:schemaLocation="/schema/beans http://www. /schema/beans/spring-beans-3.0.xsd/schema/aop http://www.springframework.o rg/schema/aop/spring-aop-3.0.xsd/schema/tx http://www.springframework.or g/schema/tx/spring-tx-3.0.xsd/schema/context http://www.springframewo /schema/context/spring-context-3.0.xsd"><context:annotation-config /><!-- 把标记了@Controller注解的类转换为bean --><context:component-scan base-package="com.mvc.controller"/> <!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 --><bean class="org.springframework.web.servlet.mvc.annotation.AnnotationM ethodHandlerAdapter"/><!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 --><bean class="org.springframework.web.servlet.view.InternalResourceView Resolver"p:prefix="/WEB-INF/view/" p:suffix=".jsp"/><bean id="multipartResolver"class="monsMultipartRe solver"p:defaultEncoding="utf-8"/></beans>applicationContext.xml代码<?xml version="1.0" encoding="UTF-8"?><beans xmlns="/schema/beans"xmlns:aop="/schema/aop" xmlns:context="http:// /schema/context"xmlns:p="/schema/p" xmlns:tx="http://www.sprin /schema/tx"xmlns:xsi="/2001/XMLSchema-instance"xsi:schemaLocation="/schema/beans http://www.springframewo /schema/beans/spring-beans-3.0.xsd/schema/context http://www.springframework.o rg/schema/context/spring-context-3.0.xsd/schema/aop /s chema/aop/spring-aop-3.0.xsd/schema/tx /sc hema/tx/spring-tx-3.0.xsd"><context:annotation-config /><context:component-scan base-package="com.mvc"/><!-- 自动扫描所有注解该路径 --><context:property-placeholder location="classpath:/hibernate.properties "/><bean id="sessionFactory"class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFacto ryBean"><property name="dataSource" ref="dataSource"/><property name="hibernateProperties"><props><prop key="hibernate.dialect">${dataSource.dialect}</prop><prop key="hibernate.hbm2ddl.auto">${dataSource.hbm2ddl.auto}</prop><prop key="hibernate.hbm2ddl.auto">update</prop></props></property><property name="packagesToScan"><list><value>com.mvc.entity</value><!-- 扫描实体类,也就是平时所说的model --></list></property></bean><bean id="transactionManager"class="org.springframework.orm.hibernate3.HibernateTransactionManager"> <property name="sessionFactory" ref="sessionFactory"/><property name="dataSource" ref="dataSource"/></bean><bean id="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${dataSource.driverClassName} "/><property name="url" value="${dataSource.url}"/><property name="username" value="${ername}"/><property name="password" value="${dataSource.password}"/></bean><!-- Dao的实现 --><bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"><property name="sessionFactory" ref="sessionFactory"/></bean><tx:annotation-driven transaction-manager="transactionManager"/><tx:annotation-driven mode="aspectj"/><aop:aspectj-autoproxy/></beans>hibernate.properties数据库连接配置dataSource.password=123ername=rootdataSource.databaseName=testdataSource.driverClassName=com.mysql.jdbc.DriverdataSource.dialect=org.hibernate.dialect.MySQL5DialectdataSource.serverName=localhost:3306dataSource.url=jdbc:mysql://localhost:3306/testdataSource.properties=user=${ername};databaseName=${dataSource.d atabaseName};serverName=${dataSource.serverName};password=${dataSource.passwor d}dataSource.hbm2ddl.auto=update配置已经完成,下面开始例子先在数据库建表,例子用的是mysql数据库CREATE TABLE `test`.`student` (`id` int(10) unsigned NOT NULL AUTO_INCREMENT, `name` varchar(45) NOT NULL,`psw` varchar(45) NOT NULL,PRIMARY KEY (`id`))建好表后,生成实体类package com.mvc.entity;import java.io.Serializable;import javax.persistence.Basic;import javax.persistence.Column;import javax.persistence.Entity;import javax.persistence.GeneratedValue;import javax.persistence.GenerationType;import javax.persistence.Id;import javax.persistence.Table;@Entity@Table(name = "student")public class Student implements Serializable {private static final long serialVersionUID = 1L;@Id@Basic(optional = false)@GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "id", nullable = false)private Integer id;@Column(name = "name")private String user;@Column(name = "psw")private String psw;public Integer getId() {return id;}public void setId(Integer id) {this.id = id;}public String getUser() {return user;}public void setUser(String user) {er = user;}public String getPsw() {return psw;}public void setPsw(String psw) {this.psw = psw;}}Dao层实现package com.mvc.dao;import java.util.List;public interface EntityDao {public List<Object> createQuery(final String queryString);public Object save(final Object model);public void update(final Object model);public void delete(final Object model);}package com.mvc.dao;import java.util.List;import org.hibernate.Query;import org.springframework.orm.hibernate3.HibernateCallback;import org.springframework.orm.hibernate3.support.HibernateDaoSupport;public class EntityDaoImpl extends HibernateDaoSupport implements EntityDao {public List<Object> createQuery(final String queryString) { return (List<Object>) getHibernateTemplate().execute(new HibernateCallback<Object>() {public Object doInHibernate(org.hibernate.Session sessio n)throws org.hibernate.HibernateException {Query query = session.createQuery(queryString);List<Object> rows = query.list();return rows;}});}public Object save(final Object model) {return getHibernateTemplate().execute(new HibernateCallback<Object>() {public Object doInHibernate(org.hibernate.Session sessio n)throws org.hibernate.HibernateException {session.save(model);return null;}});}public void update(final Object model) {getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session)throws org.hibernate.HibernateException {session.update(model);return null;}});}public void delete(final Object model) {getHibernateTemplate().execute(new HibernateCallback<Object>() { public Object doInHibernate(org.hibernate.Session session)throws org.hibernate.HibernateException {session.delete(model);return null;}});}}Dao在applicationContext.xml注入<bean id="entityDao" class="com.mvc.dao.EntityDaoImpl"><property name="sessionFactory" ref="sessionFactory"/></bean>Dao只有一个类的实现,直接供其它service层调用,如果你想更换为其它的Dao实现,也只需修改这里的配置就行了。

SpringMVC框架知识点详解

SpringMVC框架知识点详解官⽅的下载⽹址是:⼀、Spring MVC简介1.1Spring MVC⼯作流程映射器:主要是根据浏览器上输⼊的url来映射所有满⾜要求的Handle(控制器类)适配器:主要是决定调⽤哪个Handler来实现具体的业务逻辑1.2Spring MVC VS Struts21)springmvc的⼊⼝是⼀个servlet,即前端控制器;struts2⼊⼝是⼀个filter过虑器,即前端过滤器,2)springmvc是基于⽅法开发(控制器类是单例的,不可能维护实体变量),传递参数是通过⽅法形参,可以设计为单例;struts2是基于类开发(维护⼀个实体变量),传递参数是通过类的属性,只能设计为多例3)springmvc通过参数解析器是将request对象内容进⾏解析成⽅法形参,将响应数据和页⾯封装成ModelAndView对象,最后⼜将模型数据通过request对象传输到页⾯;struts采⽤值栈存储请求和响应的数据,通过OGNL存取数据4)springmvc开发运⾏速度快于struts2⼆、Spring MVC⼯程搭建(xml)2.1导⼊springioc,springweb , springmvc相关的jar包2.2在/WEB-INF/ web.xml⽂件配置SpringMVC的前端控制器DispatcherServlet(前端控制器)<!-- 注册springmvc核⼼控制器 --><servlet><!-- servlet-name名字随便写 --><servlet-name>DispatcherServlet</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><!-- 通知DispatcherServlet去指定的⽬录下加载springmvc.xml配置⽂件classpath:是在⼯程的src路径下寻找如果不配置init-param的话,控制器会⾃动寻找/WEB-INF/<servlet-name>-servlet.xml⽂件--><init-param><!-- 值是固定的,相当于键值对 --><param-name>contextConfigLocation</param-name><param-value>classpath:springmvc.xml</param-value></init-param></servlet><servlet-mapping><servlet-name>DispatcherServlet</servlet-name><url-pattern>*.action</url-pattern>//拦截请求</servlet-mapping>注:在默认情况下:springmvc框架的配置⽂件必须叫<servlet-name>-servlet.xml且必须放在/WEB-INF/⽬录下,我们可以在web.xml⽂件中,为DispatcherServlet配置⼀个初始化参数,让它去我们指定的⽬录下加载springmvc.xml配置⽂件2.3配置springmvc.xml注:该配置⽂件的命名规则遵循web.xml⽂件中核⼼控制器配置。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

在Java的Spring开发中经常使用一些注解,例如 @XXX 等等,在网上看到收集整理碎片知识,便于懒人计划^=^...过去,Spring使用的Java Bean对象必须在配置文件[一般为application.xml] 中进行配置,然后才能使用,但Spring2.5版之后,引入了配置注解功能,操作更简单,但是不了解的就抽象了,所以有必要了解一下一些注解的知识;一,首选注意,注解,注入需要的JAR包,即有common-annotations.jar 包的支持;二,要使用注解的注入功能需要在Spring配置文件[一般为application.xml]进行必要的配置才能使用注解,注入功能,例如下面;参见/blog/16700301.<beans xmlns="...">2.<!-- 添加注解驱动 -->3.<context:annotation-config/>4.5.<!-- 默认扫描的包路径 -->6.<context:component-scan base-package=".xxx"/>7.8.<!--指定默认扫描的包路径,同时指定不扫描的包,如默认扫描包下的Service不扫描-->9. <!--10.<context:component-scan base-package="xx.xxx.yyy"/>11.<context:exclude-filter type="annotation"expression="xx.xxx.yyy.Service"/>12.</context:component-scan>13. -->14.15.<!-- Spring MVC 必须的配置 -->16.<mvc:annotation-driven/>17.18.<!-- 配置js,css等静态文件直接映射到对应的文件夹,不被DispatcherServlet处理 -->19.<mvc:resources location="/resources/"mapping="/resources/**"/>20.21.<!-- 定义一些视图控制器,完成访问路径到返回视图的映射关系 -->22.<mvc:view-controller path="/"view-name="forward:/logon"/>23.<mvc:view-controller path="/permission/login"view-name="permission/login"/>24.<mvc:view-controller path="/permission/logout"view-name="permission/login"/>25.<!-- ...其他Bean的配置... -->26.</beans>其中<context:annotation-config/>的作用是隐式地向 Spring 容器注册如下四个Bean,这是注解,注入功能的驱动:AutowiredAnnotationBeanPostProcessor,CommonAnnotationBeanPostProcessor,PersistenceAnnotationBeanPostProcessor,RequiredAnnotationBeanPostProcessor具体解释例如:.如果想使用@Resource 、@PostConstruct、@PreDestroy等注解就必须声明CommonAnnotationBeanPostProcessor。

.如果想使用@PersistenceContext注解,就必须声明PersistenceAnnotationBeanPostProcessor的Bean。

.如果你想使用@Autowired注解,那么就必须事先在 Spring 容器中声明AutowiredAnnotationBeanPostProcessor Bean。

传统声明方式如下:<beanclass="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor "/>.如果想使用@Required的注解,就必须声明RequiredAnnotationBeanPostProcessor的Bean。

同样,传统的声明方式如下:<beanclass="org.springframework.beans.factory.annotation.RequiredAnnotationBeanPostProcessor"/>其中<context:component-scan base-package="xx.xxx.xxxx" />的作用是扫描指定的包,即寻找指定包内的类class文件,类似于Spring配置文件中Bean的定义,如:<bean id="..." class="..."> ,也可在该元素中增加<context:exclude-filter type="annotation" expression="xx.yy"/>指定不扫描的包;其中<mvc:annotation-driven /> 的作用是自动注册DefaultAnnotationHandlerMapping与AnnotationMethodHandlerAdapter 这两个bean, 是spring MVC为@Controllers分发请求所必须的。

是一种简写形式,完全可以手动配置替代这种简写形式,简写形式可以让初学者快速应用默认配置方案,并提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。

三,在annotaion配置注解中用@Component来表示一个通用注解,用于说明一个类是一个spring容器管理的类,也即就是该类已经被拉入到spring框架的管理中了。

而@Controller, @Service,@Repository等等是@Component的细化,这三个注解比@Component带有更多的语义,它们分别对应了控制层、服务层、持久层的类,下面逐步了解一下部分注解;1,@Component把普通pojo实例化到spring容器中,相当于配置文件中的<bean id="" class=""/>,即类的声明;@Component和<context:annotation-config/>和<context:component-scan base-package="com.xxx"/> 三者配合实现无XML配置,只通过注解配置即可将类放入Spring资源容器中。

如果用注入方式的话就需要在Spring配置文件application.xml中引入component的扫描组件,<context:annotation-config/>和<context:component-scan base-package="com.xxx">其中base-package为需要扫描的包(含所有子包)2,@Resource作用是在Spring容器里面找相应的资源,资源必须先通过Spring配置文件application.xml等方式预先加载到Spring框架容器中;/kf/201206/137806.html可通过name属性指定查找的资源名称,有时name属性可省,可注解到field或setter方法上面,例如:[html]view plain copy1.public class UserAction {2. private UserService userService;3.4. @Resource(name="userService") //或@Resource("userService")5. public void setUserService(UserService userService){erService = userService;7. }8. public void addUser(){9. userService.HelloWorld();10. }11.}3,@Autowired 和 @Resource两者都用于注入对象功能,@Autowired 按 byType 自动注入,@Resource 的作用相当于 @Autowired,但@Resource 默认按byName 自动注入罢了,@Resource 有两个属性是比较重要的,分别是 name 和 type,Spring 将@Resource 注释的 name 属性解析为 Bean 的名字,而 type 属性则解析为 Bean 的类型。

所以如果使用 name 属性,则使用 byName 的自动注入策略,而使用 type 属性时则使用 byType 自动注入策略。

如果既不指定 name 也不指定 type 属性,这时将通过反射机制使用 byName 自动注入策略。

Resource 注释类位于 Spring 发布包的 lib/j2ee/common-annotations.jar 类包中;4,@Repository该注解是用来给持久层的类定义一个名字,让Spring根据这个名字关联到这个类。

例如:1.@Repository("userDao")2.public class UserDaoImpl implements UserDao{3.//...4.}声明了UserDaoImpl ,它在Spring容器中叫userDao这个名字; 另外标签:@Autowired 用来注入,例如:1.@Autowired2.private UserDao userDao;这样就注入到Spring容器中去了,相当于我们new了这个实现类并且加入到Spring框架的容器中,我们就无需写getter、setter方法了。

相关文档
最新文档