SpringSpringMVC

来源:互联网 发布:数据库日志文件清理 编辑:程序博客网 时间:2024/06/07 13:11


SPRING

Spring是一个开源的轻量级Java SE(Java 标准版本)/Java EE(Java 企业版本)开发应用框架,其目的是用于简化企业级应用程序开发。

IOC 反转控制

谁控制谁,控制什么,为何是反转?

IoC 容器控制了对象,消费者直接通过IOC容器获得对象,不需要new; 因为由容器帮我们查找及注入依赖对象,对象只是被动的接受依赖对象,所以是反转。

IOC容器的工作内容:【创建和查找依赖对象】初始化类A-->检查A是否有依赖的对象,如果有将依赖的对象B注入到A...,IOC容器管理这些对象的生命周期

Spring容器初始化、装配及管理的对象我们通常叫它Bean,常用容器如下:

  • ClassPathXmlApplicationContext
  • ApplicationContext

Spring项目获得bean对象方式

        String configLocation = "classpath:spring-bean.xml";        ctx = new ClassPathXmlApplicationContext(configLocation);        XxxBean xxxBean= ctx.getBean(beanName,XxxBean.class);

Spring Web 项目手动获得bean对象方法

import org.springframework.beans.BeansException;import org.springframework.context.ApplicationContext;import org.springframework.context.ApplicationContextAware;public class SpringContextUtil implements ApplicationContextAware {    private static ApplicationContext applicationContext;    @Override    public void setApplicationContext(ApplicationContext applicationContext)            throws BeansException {         SpringContextUtil.applicationContext = applicationContext;    }    /**     * @return applicationContext     */    public static ApplicationContext getApplicationContext(){        return applicationContext;    }    /**     * @param name     * @return bean     */    public static Object getBean(String name) throws BeansException{        return applicationContext.getBean(name);    }}
DI 依赖注入

DI 和 IOC 是同一个概念的不同角度的描述 IOC描述的是设计思想。
DI主要描述是对象间的关系。 被注入的对象依赖于依赖对象。DI依赖IOC

AOP
  • 切入点(Pointcut)
  • 通知(Advice)
  • 方面/切面(Aspect)
<bean id="hello" class="com.mguas.aop.HelloAOP"/><aop:config><aop:pointcut id="pointcut" expression="execution(* com.mguas..*.*(..))"/>    <aop:aspect ref="hello">        <aop:before pointcut-ref="pointcut" method="beforeAdvice"/>        <aop:after pointcut-ref="pointcut" method="afterFinallyAdvice"/>    </aop:aspect></aop:config>

动态代理

SPRING MVC

基本原理
前端控制器(DispatcherServlet)请求到处理器映射(HandlerMapping)处理器适配器(HandlerAdapter)视图解析器(ViewResolver)处理器或页面控制器(Controller)SPRING MVC 实现原理:http请求-->DispatcherServlet 拦截并将请求转向spring mvc -->HandlerMapping 找到并保存请求和处理函数之间的关系-->DispatcherServlet-->HandlerAdapter调用处理函数-->Controller处理处理-->DispatcherServlet-->ViewResolver视图解析
web.xml
<?xml version="1.0" encoding="UTF-8"?><web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">    <context-param>        <param-name>contextConfigLocation</param-name>        <param-value>/WEB-INF/spring/root-context.xml</param-value>    </context-param>        <listener>        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>    </listener>    <filter>        <filter-name>springEncoding</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>        <init-param>            <param-name>forceEncoding</param-name>            <param-value>true</param-value>        </init-param>    </filter>    <filter-mapping>        <filter-name>springEncoding</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>    <servlet>        <servlet-name>appServlet</servlet-name>        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>        <init-param>            <param-name>contextConfigLocation</param-name>            <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value>        </init-param>        <load-on-startup>1</load-on-startup>    </servlet>    <servlet-mapping>        <servlet-name>appServlet</servlet-name>        <url-pattern>/</url-pattern>    </servlet-mapping></web-app>
load-on-startup:表示启动容器时初始化该Servleturl-pattern:表示哪些请求交给Spring Web MVC处理    常见拦截方式:    *.do、 *.htm、 *.json     /(会导致静态文件无法访问,可以解决)     /*(会导致访问jsp时再次拦截,导致无法正常访问jsp,纯纯的数据库接口可以这么写。不建议)init-param param-value:指定SPRING MVC 配置文件位置,多个逗号隔开context-param param-value:上下文配置文件listener:上下文监听
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?><beans:beans xmlns="http://www.springframework.org/schema/mvc"    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"    xmlns:beans="http://www.springframework.org/schema/beans"    xmlns:context="http://www.springframework.org/schema/context"    xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd        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">    <!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->    <!-- Enables the Spring MVC @Controller programming model -->    <annotation-driven />    <!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources directory -->    <resources mapping="/resources/**" location="/resources/" />    <!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->    <beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">        <beans:property name="prefix" value="/WEB-INF/" />        <beans:property name="suffix" value=".jsp" />    </beans:bean>    <context:component-scan base-package="com.magus.lottery.controller">        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />    </context:component-scan></beans:beans>
 <annotation-driven /> 支持注解 <resources .../> 静态文件,不被前置拦截器拦截 InternalResourceViewResolver 视图实现      prefix 前缀      suffix 后缀 context:component-scan 自动扫描包   
spring-bean.xml
<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: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-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 http://www.springframework.org/schema/context/spring-context-3.0.xsd" xmlns:context="http://www.springframework.org/schema/context"    default-autowire="byName">        <context:component-scan base-package="com"></context:component-scan>        <context:property-placeholder location="classpath:jdbc.properties" />    <bean id="dataSource"         class="com.mchange.v2.c3p0.ComboPooledDataSource"         destroy-method="close">         <property name="driverClass" value="${driverClass}" />         <property name="jdbcUrl" value="${jdbcUrl}" />         <property name="user" value="${user}" />         <property name="password" value="${password}" />         <property name="acquireIncrement" value="10" />         <property name="acquireRetryAttempts" value="5" />         <property name="acquireRetryDelay" value="50" />         <property name="checkoutTimeout" value="60000" />         <property name="initialPoolSize" value="5" />         <property name="maxPoolSize" value="15" />         <property name="maxStatementsPerConnection" value="1000"/>     </bean>    <bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">        <property name="dataSource" ref="dataSource" />        <property name="hibernateProperties">            <props>                       <prop key="hibernate.dialect">org.hibernate.dialect.PostgreSQLDialect</prop>                <prop key="hibernate.show_sql">true</prop>                <prop key="hibernate.format_sql">true</prop>                <prop key="hibernate.current_session_context_class">org.springframework.orm.hibernate4.SpringSessionContext</prop>                <!--                 <prop key="hibernate.hbm2ddl.auto">update</prop>                 -->            </props>        </property>        <property name="packagesToScan" value="com.magus.lottery.entity"/>    </bean>    <bean id="transactionManager"          class="org.springframework.orm.hibernate4.HibernateTransactionManager">          <property name="sessionFactory" ref="sessionFactory" />      </bean>      <tx:annotation-driven transaction-manager="transactionManager"/>     <aop:aspectj-autoproxy expose-proxy="true"/></beans>
spring mvc 常见注解
@Controller  声明控制器 处理器@Service    声明Service组件 @Repository 声明Dao组件@Component   声明组件@RequestMapping("/menu")  请求映射@Resource(name="beanName")  注入对象@Autowired 注入对象@Transactional 声明事务,用于service层@ResponseBody  声明响应结果为数据,不进行view渲染@Scope("prototype")   设定bean的作用域,prototype、singleton、request、session
0 0
原创粉丝点击