怎么使用注解方式(Annotation)来搭配spring 实例详解
如何使用注解方式(Annotation)来搭配spring 实例详解
Struts+Spring用到现在,它的好处大家是有目共睹的,可是在遇到一个业务比较复杂的项目的时候,会发现Struts和Spring的配置文件又复杂又长,尽管将Spring配置文件分开也只是治标不治本。JDK1.5的出现,带出了一个新技术,它就是Annotation 注解式Spring自动装配,以下为相关代码(从“前”向“后”)
register.jsp
提交之后,跳过了struts,直接去寻找java了,所以可以抛弃struts了,具体见以下配置文件
web.xml 在web.xml中配置spring的自动扫描和自动装配的后缀(.do)
annomvc-servlet.xml 配置了annotation自动装配的一些参数
在com.myweb.action中扫描
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>
提交之后,跳过了struts,直接去寻找java了,所以可以抛弃struts了,具体见以下配置文件
web.xml 在web.xml中配置spring的自动扫描和自动装配的后缀(.do)
<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>
annomvc-servlet.xml 配置了annotation自动装配的一些参数
<?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 class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <!-- ③:对模型视图名称的解析,即在模型视图名称添加前后缀 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix="/" p:suffix=".jsp"/> </beans>
在com.myweb.action中扫描
//自动装配DAO @Autowired private SysUserBasicDAO sysUserBasicDAO; //就是这里响应的jsp中的action @RequestMapping("/sysUser/register") //从jsp的form中自动装配SysUserBasic 需要注意的是form中的控件名必须和SysUserBasic中定义的名字相符合 public ModelAndView addSysUserBasic(SysUserBasic sysUserBasic){ sysUserBasicDAO.save(sysUserBasic); return new ModelAndView("index"); }