现在主流的开放框架,除了Struts MVC 就是spring的MVC了
今天就总结下SpringMVC,掌握它的配置及原理。
一、Spring MVC环境搭建:(Spring 2.5.6 + Hibernate 3.2.0)
1. jar包引入
Spring 2.5.6: spring.jar、spring-webmvc.jar、commons-logging.jar、cglib-nodep-2.1_3.jar
Hibernate 3.6.8:hibernate3.jar、hibernate-jpa-2.0-api-1.0.1.Final.jar、antlr-2.7.6.jar、commons-collections-3.1、dom4j-1.6.1.jar、
javassist-3.12.0.GA.jar、jta-1.1.jar、slf4j-api-1.6.1.jar、slf4j-nop-1.6.4.jar、相应数据库的驱动jar包
2. web.xml配置(部分)
<!-- spring MVC配置 -->
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 可以自定义servlet.xml配置文件的位置和名称,默认为WEB-INF目录下,名称为[<servlet-name>]-servlet.xml,如spring-servlet.xml
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring-servlet.xml</param-value> 默认
</init-param>
-->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!-- spring 配置 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 指定spring Bean配置文件所在目录 ,默认目录是在WEB-INF目录下-->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContexts/**/*.xml </param-value>
</context-param>
3. spring-servlet.xml配置【配置mvc注解,扫描使用注解类所在包,自动创建bean自动依赖注入,完成请求和注解POJO映射,跳转页面路径解析】
spring-servlet这个名字是因为上面web.xml中<servlet-name>标签配的值为spring(<servlet-name>spring</servlet-name>),再加上“-servlet”后缀而形成的spring-servlet.xml文件名,如果改为springMVC,对应的文件名则为springMVC-servlet.xml。
<?
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-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/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/context <a
href
=
"http://www.springframework.org/schema/context/spring-context-3.0.xsd"
>http://www.springframework.org/schema/context/spring-context-3.0.xsd</
a
>">
<!-- 启用spring mvc 注解 -->
<
context:annotation-config
/>
context
是spring2.1添加的新的schema命名空间
注释本身是不会做任何事情的,它仅提供元数据信息。要使元数据信息真正起作用,必须让负责处理这些元数据的处理器工作起来,
下面4个类就是处理这些注释元数据的处理器,按照传统的方式《bean id = ''>很笨拙,所有就有了上面的简便写法
其实他隐式地向Spring容器注册4个BeanPostProcessor:
Autowired AnnotationBeanPostProcessor、
Common AnnotationBeanPostProcessor、
PersistenceAnnotationBeanPostProcessor、
Required AnnotationBeanPostProcessor
<!-- 支持异步方法执行 ,查看模板技术一文-->
<task:annotation-driven/>
<!--
让下面截图中bean定义注解的类工作起来,用context:compoent-scan
设置使用注解的类所在的jar包[对web包中的所有类进行扫描类包及其递归子包中所有的类都会被处理] ,以完成Bean创建和自动依赖注入的功能
这里,所有通过<bean>元素定义Bean的配置内容已经被移除,仅需要添加一行<context:component-scan />配置就解决所有问题了——Spring XML配置文件得到了极致的简化
=========================特别注意:==================================
<context:component-scan />配置项
1.启用了对类包进行扫描以实施注释驱动Bean定义的功能,
2.同时还启用了注释驱动自动注入的功能(即还隐式地在内部注册了AutowiredAnnotationBeanPostProcessor和CommonAnnotationBeanPostProcessor),
因此当使用<context:component-scan />后,就可以将<context:annotation-config />移除了。
-->
<
context:component-scan
base-package
=
"com.jt"
>
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
</
context:component-scan
>
<!-- 完成请求和注解POJO的映射 -->
<
bean
class
=
"org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
/>
<!-- 对转向页面的路径解析。prefix:前缀, suffix:后缀 -->
<
bean
class
=
"org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix
=
"/jsp/"
p:suffix
=
".jsp"
/>
<!-- 文件上传解析实体 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="defaultEncoding"><value>UTF-8</value></property>
<!-- 上传文件大小限制为20M -->
<property name="maxUploadSize"><value>20971520</value></property>
<property name="maxInMemorySize"> <value>4096</value></property>
</bean>
</
beans
>
4. applicationContext.xml配置【数据库连接和事物】
<?
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:aop
=
"http://www.springframework.org/schema/aop"
xmlns:tx
=
"http://www.springframework.org/schema/tx"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd">
<
bean
id
=
"dataSource"
class
=
"org.apache.commons.dbcp.BasicDataSource"
>
<
property
name
=
"driverClassName" value="com.mysql.jdbc.Driver"
>
</
property
>
<
property
name
=
"url" value="jdbc:mysql://xxxxxxxxx:3306/xiaoyang?allowMultiQueries=true"
>
</
property
>
<
property
name
=
"username" value="aaaaaaaaaaa"
>
</
property
>
<
property
name
=
"passworkd" value="bbbbbbbbbbb"
>
</
property
>
<property name="validationQuery" value="select count(*) from xy_invitation_code"></property>
<property name="testWhileIdle" value="true"></property>
<property name="testOnBorrow" value="true"></property>
<property name="initialSize" value="10"></property>
<property name="maxActive" value="50"></property>
<property name="maxIdle" value="10"></property>
</
bean
>
<!-- 配置数据源 -->
<
bean
id
=
"sessionFactory"
class
=
"org.springframework.orm.hibernate3.LocalSessionFactoryBean"
>
<
property
name
=
"dataSource" ref = "dataSource"
>
</
property
>
<property name="packagesToScan" value="com.jt.*" /><!--注意这里配置了扫描的包,也就是对应的spring POJO实体-->
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.show_sql">false</prop>
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</prop>
<prop key="hibernate.cache.use_query_cache">false</prop>
<prop key="hibernate.jdbc.batch_size">50</prop>
<prop key="hibernate.cache.use_second_level_cache">false</prop>
<prop key="hibernate.connection.autocommit">false</prop>
</props>
</property>
</
bean
>
<!-- 将事务与Hibernate关联 -->
<
bean
id
=
"
transactionManager
"
class
=
"org.springframework.orm.hibernate3.HibernateTransactionManager"
>
<
property
name
=
"sessionFactory" ref="sessionFactory"
>
</
property
>
</
bean
>
<!-- 事务(注解 )-->
<
tx:annotation-driven
transaction-manager
=
"
transactionManager
"
proxy-target-class
=
"true"
/>
bean
id="
transactionInterceptor
"
<
property
name="
transactionManager
" ref="
transactionManager
" /><
property
name="
transactionAttributes
"><props>
<prop key="get*">PROPAGATION_REQUIRED</prop>
<!-- 这里配置readOnly过虑,则该方法内部不能对数据库进行写操作,只能读-->
<prop key="find*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="query*">PROPAGATION_REQUIRED,readOnly</prop>
<prop key="add*">PROPAGATION_REQUIRED</prop>
<prop key="insert*">PROPAGATION_REQUIRED</prop>
<prop key="edit*">PROPAGATION_REQUIRED</prop>
<prop key="update*">PROPAGATION_REQUIRED</prop>
<prop key="save*">PROPAGATION_REQUIRED</prop>
<prop key="remove*">PROPAGATION_REQUIRED</prop>
<prop key="delete*">PROPAGATION_REQUIRED</prop>
<prop key="getMessage">PROPAGATION_REQUIRED</prop>
<prop key="*">PROPAGATION_REQUIRED,-java.lang.Exception</prop>
</props>
</property>
</
bean
><
bean
id="
ProxyCreator
" class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"><property name="beanNames" value="*Service,*ServiceImpl,*Dao,*DaoImpl" />
<property name="interceptorNames" value="transactionInterceptor" />
</
bean
><import resource="applicationContext-freemarker.xml" />
<import resource="applicationContext-email.xml" />
<!-- 测试Service -->
<
bean
id
=
"loginService"
class
=
"service.LoginService"
></
bean
>
<!-- 测试Dao -->
<
bean
id
=
"hibernateDao"
class
=
"dao.HibernateDao"
>
<
property
name
=
"sessionFactory"
ref
=
"sessionFactory"
></
property
>
</
bean
>
</
beans
>
spring的注解用法:[目标:从XML配置文件中完全移除Bean定义的配置]
第一部分:自动注入Bean【通过@Reporitory @Service @Controller】
第二部分:Bean中自动注入属性 【通过@Autowired或@Resource来实现在Bean中自动注入的功能】
第三部分:让上面注册的注解工作起来
使用Spring注解完成Bean的定义 :
=============================================收纳下别人的总结=================================================
1. 使用Spring注解来注入属性
1.1. 使用注解以前我们是怎样注入属性的
类的实现:
- public class UserManagerImpl implements UserManager {
- private UserDao userDao;
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- ...
- }
配置文件:
- <bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl">
- <property name="userDao" ref="userDao" />
- </bean>
- <bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">
- <property name="sessionFactory" ref="mySessionFactory" />
- </bean>
1.2. 引入@Autowired注解(不推荐使用,建议使用@Resource)
类的实现(对成员变量进行标注)
- public class UserManagerImpl implements UserManager {
- @Autowired
- private UserDao userDao;
- ...
- }
或者(对方法进行标注)
- public class UserManagerImpl implements UserManager {
- private UserDao userDao;
- @Autowired
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
- ...
- }
配置文件
- <bean id="userManagerImpl" class="com.kedacom.spring.annotation.service.UserManagerImpl" />
- <bean id="userDao" class="com.kedacom.spring.annotation.persistence.UserDaoImpl">
- <property name="sessionFactory" ref="mySessionFactory" />
- </bean>
@Autowired可以对成员变量、方法和构造函数进行标注,来完成自动装配的工作。以上两种不同实现方式中,@Autowired的标注位置不同,它们都会在Spring在初始化userManagerImpl这个bean时,自动装配userDao这个属性,区别是:第一种实现中,Spring会直接将UserDao类型的唯一一个bean赋值给userDao这个成员变量;第二种实现中,Spring会调用setUserDao方法来将UserDao类型的唯一一个bean装配到userDao这个属性。
1.3. 让@Autowired工作起来
要使@Autowired能够工作,还需要在配置文件中加入以下代码
- <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
1.4. @Qualifier
@Autowired是根据类型进行自动装配的。在上面的例子中,如果当Spring上下文中存在不止一个UserDao类型的bean时,就会抛出BeanCreationException异常;如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。我们可以使用@Qualifier配合@Autowired来解决这些问题。
1. 可能存在多个UserDao实例
- @Autowired
- public void setUserDao(@Qualifier("userDao") UserDao userDao) {
- this.userDao = userDao;
- }
这样,Spring会找到id为userDao的bean进行装配。
2. 可能不存在UserDao实例
- @Autowired(required = false)
- public void setUserDao(UserDao userDao) {
- this.userDao = userDao;
- }
Spring 不但支持自己定义的@Autowired注解,还支持几个由JSR-250规范定义的注解,它们分别是
@Resource、@PostConstruct以及@PreDestroy。
@Resource的作用相当于@Autowired,只不过
@Autowired按byType自动注入,而
@Resource默认按byName自动注入。
@Resource有两个属性是比较重要的,分别是name和type,Spring将@Resource注解的
name属性解析为bean的名字,而
type属性则解析为bean的类型。
@Resource装配顺序
- 如果同时指定了name和type,则从Spring上下文中找到唯一匹配的bean进行装配,找不到则抛出异常
- 如果指定了name,则从上下文中查找名称(id)匹配的bean进行装配,找不到则抛出异常
- 如果指定了type,则从上下文中找到类型匹配的唯一bean进行装配,找不到或者找到多个,都会抛出异常
- 如果既没有指定name,又没有指定type,则自动按照byName方式进行装配【反射机制】(见2);如果没有匹配,则回退为一个原始类型(UserDao)进行匹配,如果匹配则自动装配;
- 1.6. @PostConstruct(JSR-250)
在方法上加上注解@PostConstruct,这个方法就会在Bean初始化之后被Spring容器执行 - (注:Bean初始化包括,实例化Bean,并装配Bean的属性(依赖注入))。
它的一个典型的应用场景是,当你需要往Bean里注入一个其父类中定义的属性,而你又无法复写父类的属性或属性的setter方法时,如:
- public class UserDaoImpl extends HibernateDaoSupport implements UserDao {
- private SessionFactory mySessionFacotry;
- @Resource
- public void setMySessionFacotry(SessionFactory sessionFacotry) {
- this.mySessionFacotry = sessionFacotry;
- }
- @PostConstruct
- public void injectSessionFactory() {
- super.setSessionFactory(mySessionFacotry);
- }
- ...
- }
这里通过@PostConstruct,为UserDaoImpl的父类里定义的一个sessionFactory私有属性,注入了我们自己定义的sessionFactory(父类的setSessionFactory方法为final,不可复写),之后我们就可以通过调用super.getSessionFactory()来访问该属性了。
1.7. @PreDestroy(JSR-250)
在方法上加上注解@PreDestroy,这个方法就会在Bean初始化之后被Spring容器执行。由于我们当前还没有需要用到它的场景,这里不不去演示。其用法同@PostConstruct。