Spring 入门配置实例


从登陆模块介绍spring最简单的配置

1、web.xml中配置主控servlet和servlet-mapping,如下:

<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
2、web.xml中配置需要加载的spring配置文件,如applicationContext.xml(项目简单的情况下,单个配置文件就够了)或其它名字(多个用逗号分隔),如下:

<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:*-beans.xml</param-value>
	</context-param>

3、spring mvc默认拥有一个spring的配置文件,即<servlet-name>-servlet.xml,会自动与其它配置文件进行拼装加载。在该文件中,需要配置扫描及试图解析器,如下:

<context:component-scan base-package="com.xxx.web" >
    </context:component-scan>

<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
4、web.xml中配置负责启动spring容器的监听器,如下:

<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

spring容器的启动和关闭由Web容器的启动和关闭事件触发,所以设置监听器以监听。ContextLoaderListener继承自ServletContextListener

5、声明@Controller,@RequestMapping类处理请求,并返回login.jsp页面,如下:

@Controller
public class HelloController {
	@RequestMapping(value = "/index.html")
	public String loginPage() {
		return "login";
	}
}
6、输入用户名/密码后进行登陆,处理过程需要业务层对用户名和密码进行校验是否存在数据库中,所以在业务层内部还需要与持久层进行交互。如果验证不成功,则返回登陆页面,提示错误。如果验证成功,则获取用户信息,设置最后访问的ip,访问时间,新增登陆积分,并更新到数据库中,此处也需要与持久层交互。

7、建立领域对象User和LoginLog,前者代表用户信息,后者代表日志信息,分别对应数据表t_user,t_login_log。领域对象一般需要实现serializable接口。

8、根据MVC模型特点,一般在控制器类中注入业务层类,如UserService;而在UserService类中注入DAO类与数据库进行交互。

9、首先定义与数据库交互的DAO层,如UserDao。它提供根据用户名和密码进行数据库查询校验的方法,根据用户名获取User领域对象的方法,更新信息到数据库的方法等。如下:

@Repository
public class UserDao{
	@Autowired
	private JdbcTemplate jdbcTemplate;
	
	public int getMatchCount(String userName, String password){
		String sql = "select count(*) from t_user where user_name = ? and password = ? ";
		return jdbcTemplate.queryForInt(sql, new Object[]{userName, password};
	}
	
	//todo 其它方法
}

在spring配置文件中配置扫描、数据源及其它Bean

10、定义业务层UserService,如下:

@Service
public class UserService{
    @AutoWired
    private UserDao userDao;

    ....
}
同样需要在spring配置文件中配置扫描的包及事务管理器,其它命名空间。

11、单元测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/applicationContext.xml"})//启动spring容器
public class TestUserService{
    @Autowired
    private UserService userService;//注入spring容器中的Bean
    
    @Test
    public void hasMatchUser(){
        boolean b1 = userService.func();
        assertTrue(...)
    }
}

12、配置实例:

(1)web.xml:

<web-app version="2.4"
	xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
	</filter>

	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>

	<display-name>xxx</display-name>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath*:*-beans.xml</param-value>
	</context-param>

	<!--log4j-->
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>
	<listener>
		<listener-class>
			org.springframework.web.util.Log4jConfigListener
		</listener-class>
	</listener>
	<!--log4j-->

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
		</init-param>
        <init-param>
            <param-name>detectAllHandlerExceptionResolvers</param-name><!-- 取消其自动注册的异常解析器 -->
            <param-value>false</param-value>
        </init-param>
        <init-param>
            <param-name>throwExceptionIfNoHandlerFound</param-name>
            <param-value>true</param-value>
        </init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>

	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<servlet-mapping>
		<servlet-name>default</servlet-name>
		<url-pattern>/assets/*</url-pattern>
	</servlet-mapping>


    <!-- druid start-->

    <filter>
        <filter-name>DruidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*</param-value>
        </init-param>
        <init-param>
            <param-name>sessionStatMaxCount</param-name>
            <param-value>1000</param-value>
        </init-param>
        <init-param>
            <param-name>principalCookieName</param-name>
            <param-value>__bigdata</param-value>
        </init-param>
        <init-param>
            <param-name>profileEnable</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>

    <filter-mapping>
        <filter-name>DruidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
        <init-param>
            <!-- 允许清空统计数据 -->
            <param-name>resetEnable</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>loginUsername</param-name>
            <param-value>root</param-value>
        </init-param>
        <init-param>
            <param-name>loginPassword</param-name>
            <param-value>rootpass</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

    <!-- druid end-->
	<session-config>
		<session-timeout>43200</session-timeout>
	</session-config>
</web-app>
(2)servlet-name-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">


    <!--声明使用注解 -->
    <context:annotation-config />

    <!--自动注册controller -->

    <context:component-scan base-package="xxx.controller" >
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
        <context:exclude-filter  type="annotation" expression="org.springframework.stereotype.Service"/>
    </context:component-scan>


    <mvc:annotation-driven />


    <mvc:interceptors>
        <bean class="xxx.interceptor.LoginInterceptor"/>
        <bean class="xxx.interceptor.XXXInterceptor"/>
    </mvc:interceptors>


    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

    <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor" />
    <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype">
        <property name="patterns">
            <list>
                <value>xxx.web.service.*</value>
                <value>xxx.web.controller.*</value>
            </list>
        </property>
    </bean>

    <aop:aspectj-autoproxy proxy-target-class="true"/>
    <bean class="xxx.web.common.LogAspect" />

    <aop:config proxy-target-class="true">
        <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" />
    </aop:config>

    <!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="utf-8" />
        <property name="maxUploadSize" value="102400" />
        <property name="maxInMemorySize" value="102400" />
    </bean>

</beans>
(3)other-beans.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:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">


    <!-- enable autowire -->
    <context:annotation-config />

    <!-- enable transaction demarcation with annotations -->
    <tx:annotation-driven/>


    <bean id="messageConverters" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter" />
    <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
        <property name="messageConverters" ref="messageConverters">
        </property>
    </bean>

    <bean id="handlerExceptionResolver" class="xxx.web.common.AnnotationHandlerMethodExceptionResolver">
        <property name="defaultErrorView" value="common/500"/><!-- 错误页面 -->
        <property name="defaultNotFoundView" value="common/404"/><!-- 404页面 -->
        <property name="messageConverters" ref="messageConverters"/>
    </bean>

    <bean id="springQtzJobMethod" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
        <property name="targetObject">
            <bean class="xxx.web.common.MetricsJob">
                <property name="metricsService" ref="metricsService"/>
            </bean>
        </property>
        <property name="targetMethod" value="execute"/>

    </bean>

    <bean id="dailyTaskCronTriggerBean" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
        <property name="jobDetail" ref="springQtzJobMethod"></property>
        <!-- 每隔两分钟触发   -->
        <property name="cronExpression" value="0 */5 * * * ?"></property>
    </bean>

    <bean id="SpringJobSchedulerFactoryBean" class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
        <property name="triggers">
            <list>
                <ref bean="dailyTaskCronTriggerBean"/>
            </list>
        </property>
    </bean>

</beans>
okay!!!


你可能感兴趣的:(spring)