如何使用注解方式(Annotation)来搭配spring 实例详解
Struts+Spring用到现在,它的好处大家是有目共睹的,可是在遇到一个业务比较复杂的项目的时候,会发现Struts和Spring的配置文件又复杂又长,尽管将Spring配置文件分开也只是治标不治本。JDK1.5的出现,带出了一个新技术,它就是Annotation 注解式Spring自动装配,以下为相关代码(从“前”向“后”)
register.jsp
<form action="register.do" method="post"> <input type="text" id="stUserId" name="stUserId" /> <input type="text" id="stUserName" name="stUserName" /> <input type="submit" value="submit"/></form>
<servlet> <servlet-name>annomvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>annomvc</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping>
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <!-- ①:对web包中的所有类进行扫描,以完成Bean创建和自动依赖注入的功能 --> <context:component-scan base-package="com.myweb.action"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- ②:启动Spring MVC的注解功能,完成请求和注解POJO的映射 --> <bean p:prefix="/" p:suffix=".jsp"/></beans>
//自动装配DAO@Autowiredprivate SysUserBasicDAO sysUserBasicDAO;//就是这里响应的jsp中的action@RequestMapping("/sysUser/register")//从jsp的form中自动装配SysUserBasic 需要注意的是form中的控件名必须和SysUserBasic中定义的名字相符合public ModelAndView addSysUserBasic(SysUserBasic sysUserBasic){ sysUserBasicDAO.save(sysUserBasic); return new ModelAndView("index");}