spring

一、入门篇

SSM框架整合

1、web.xml(加载spring容器listener,解决post乱码,springmvc的前端控制器)

<?xml version="1.0" encoding="UTF-8"?>

<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

     id="WebApp_ID" version="2.5">

     <display-name>taotao-manager-web</display-name>

     <welcome-file-list>

         <welcome-file>login.html</welcome-file>

     </welcome-file-list>

     <!-- 加载spring容器 -->

     <context-param>

         <param-name>contextConfigLocation</param-name>

         <param-value>classpath:spring/applicationContext*.xml</param-value>

     </context-param>

     <listener>

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

     </listener>

     <!-- 解决post乱码 -->

     <filter>

         <filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>

         <url-pattern>/*</url-pattern>

     </filter-mapping>

     <!-- springmvc的前端控制器 -->

     <servlet>

         <servlet-name>taotao-manager</servlet-name>

         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

         <!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocationspringmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->

         <init-param>

              <param-name>contextConfigLocation</param-name>

              <param-value>classpath:spring/springmvc.xml</param-value>

         </init-param>

         <load-on-startup>1</load-on-startup>

     </servlet>

     <servlet-mapping>

         <servlet-name>taotao-manager</servlet-name>

         <url-pattern>/</url-pattern>

     </servlet-mapping>

</web-app>

2、springmvc.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"

     xmlns:mvc="http://www.springframework.org/schema/mvc"

     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd

        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd

        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

 

     <context:component-scan base-package="com.taotao.controller" />

    <!--<mvc:annotation-driven>会自动注册RequestMappingHandlerMapping与RequestMappingHandlerAdapter两个Bean,这是Spring MVC为@Controller分发请求所必需的,并且提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持读写XML的支持(JAXB)和读写JSON的支持(默认Jackson)等功能。-->

     <mvc:annotation-driven />

     <bean

         class="org.springframework.web.servlet.view.InternalResourceViewResolver">

         <property name="prefix" value="/WEB-INF/jsp/" />

         <property name="suffix" value=".jsp" />

     </bean>

</beans>

3、applicationContext-service.xml(注解)

 

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

 

         <context:component-scan base-package="com.taotao.service"/>

 

</beans>

4、applicationContext-trans.xml事物管理(数据源、事物管理器、事物传播、切面)

 

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

     <!-- 事务管理器 -->

     <bean id="transactionManager"

         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">

         <!-- 数据源 -->

         <property name="dataSource" ref="dataSource" />

     </bean>

     <!-- 通知 -->

     <tx:advice id="txAdvice" transaction-manager="transactionManager">

         <tx:attributes>

              <!-- 传播行为 -->

              <tx:method name="save*" propagation="REQUIRED" />

              <tx:method name="insert*" propagation="REQUIRED" />

              <tx:method name="add*" propagation="REQUIRED" />

              <tx:method name="create*" propagation="REQUIRED" />

              <tx:method name="delete*" propagation="REQUIRED" />

              <tx:method name="update*" propagation="REQUIRED" />

              <tx:method name="find*" propagation="SUPPORTS" read-only="true" />

              <tx:method name="select*" propagation="SUPPORTS" read-only="true" />

              <tx:method name="get*" propagation="SUPPORTS" read-only="true" />

         </tx:attributes>

     </tx:advice>

     <!-- 切面 -->

     <aop:config>

         <aop:advisor advice-ref="txAdvice"

              pointcut="execution(* com.taotao.service.*.*(..))" />

     </aop:config>

</beans>

5、applicationContext-dao.xml(数据源)

 

<beans xmlns="http://www.springframework.org/schema/beans"

     xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"

     xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"

     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd

     http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd

     http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd

     http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">

 

     <!-- 数据库连接池 -->

     <!-- 加载配置文件 -->

    <!--多个文件之间以“,”分隔,java文件使用@Value("${sql.name}")-->

     <context:property-placeholder location="classpath:properties/*.properties" />

     <!-- 数据库连接池 -->

     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"

         destroy-method="close">

         <property name="url" value="${jdbc.url}" />

         <property name="username" value="${jdbc.username}" />

         <property name="password" value="${jdbc.password}" />

          <property name="driverClassName" value="${jdbc.driver}" />

         <property name="maxActive" value="10" />

         <property name="minIdle" value="5" />

     </bean>

     <!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->

     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">

         <!-- 数据库连接池 -->

         <property name="dataSource" ref="dataSource" />

         <!-- 加载mybatis的全局配置文件 -->

         <property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />

     </bean>

     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">

         <property name="basePackage" value="com.taotao.mapper" />

     </bean>

</beans>

6、db.properties

 

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql://localhost:3306/taotao?characterEncoding=utf-8

jdbc.username=root

jdbc.password=root

springmvc三种静态资源处理

1、web.xml中设置*.do

 

11 <servlet-mapping>
12     <servlet-name>SpringMVC</servlet-name>
13     <url-pattern>*.do</url-pattern>
14 </servlet-mapping>

2、springmvc.xml使用org.springframework.web.servlet.view.InternalResourceViewResolver

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

         <property name="prefix" value="/WEB-INF/jsp/" />

         <property name="suffix" value=".jsp" />

     </bean>

3、在spring-mvc.xml中启用默认Servlet

 

<mvc:default-servlet-handler/>

    在web.xml中增加对静态资源的处理

 

1 <servlet-mapping>    
2     <servlet-name>default</servlet-name>    
3     <url-pattern>*.js</url-pattern>    
4     <url-pattern>*.css</url-pattern>    
5     <url-pattern>/assets/*"</url-pattern>    
6     <url-pattern>/images/*</url-pattern>    
7 </servlet-mapping> 

 

实体类使用配置方式和注解方式

1、配置:有构造有属性的实体

<bean id="exampleBean" class="examples.ExampleBean"> 
<constructor-arg index="0" value="7500000"/> 
<constructor-arg index="1" value="42"/> 

</bean> 

2、注解:

@Component :标准一个普通的spring Bean类。 
@Repository:标注一个DAO组件类。 
@Service:标注一个业务逻辑组件类。 
@Controller:标注一个控制器组件类。 
@Autowired按bytype装配对象。
@resource默认按照ByName自动注入,两个重要的属性:name和type,而Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
@RequestMapping可以用于类和方法上。@RequestMapping (value= "testMethod" , method=RequestMethod. GET, params={ "param1=value1" , "param2" , "!param3" })  当没有其他参数value可省略,params指定包含哪些参数才让该方法处理;
@ResponseBody以json格式返回return对象;
@RequestParam,@RequestParam(value="id", defaultValue="0")long parentid,可以多个;
@PathVariable,结合@RequestMapping("/category/{cid}")使用;

    @RequestMapping("/list")
    @ResponseBody
    public EasyUIResult getlist(@RequestParam(defaultValue="1")Integer page, 
            @RequestParam(defaultValue="30")Integer rows) throws Exception {
        EasyUIResult result = service.getList(page, rows);
        return result;
    }

@PostConstruct,在对象的参数设置完成之后自动执行(虚拟构造)。相当于init-method。
@PreDestroy,在context.close()执行后被调用。相当于destroy-method。

二、精通篇

1、springmvc
(1)七个接口
DispatcherServlet 请求分发(在web.xml中配置servlet-mapping)
HandleMapping 将请求映射到Controller(@Controller)
HandleAdapter 将请求映射到方法(@RequestMapping)
HandleIntercepter 拦截器
Controller 控制器
riewResolve 视图映射(当方法上面没有写ResponseBody,底层会将方法的返回值封装为ModelAndView对象)
view 视图处理

<context:component-scan />
是spring2.5版本提供的一个强大的组件扫描功能。它能够自动从classpath中扫描、检测和实例化你的bean。当我们在spring配置文件当中添加了<context:component-scan base-package="com.taotao.controller" />这个xml元素,就表示启动spring的组件扫描功能。指定属性base-package(包名),表示将扫描base-package包或者子包下面的java文件,如果扫描到有@controller、@Service、@Repository、@Component等注解的java类,就会将这些类注册为bean。还可以使用分号来分隔多个扫描包。 
<context:annotation-config/>
向spring容器注入AutowiredAnnotationBeanPostProcessor、CommonAnnotationBeanPostProcessor、PersistenceAnnotationBeanPostProcessor 及RequiredAnnotationBeanPostProcessor四个beanPostProcessor。
如果想使用@Autowired注解生效,能够自动注入,就必须向spring容器声明AutowiredAnnotationBeanPostProcessor
如果想使用@Resource、@PostConstruct、@PreDestroy等注解,就要声明CommonAnnotationBeanPostProcessor。 
如果想使用@PersistenceContext就得声明PersistenceAnnotationBeanPostProcessor 。 
如果想使用@Required注解得声明RequiredAnnotationBeanPostProcessor。
如果在配置文件中配置了<context:component-scan />,就不用在配置<context:annotation-config/>,因为前者已经包含了后者。
<mvc:annotation-driven />
一般我们采用@RequestMapping注解来完成映射关系,还必须向上下文中注册DefaultAnnotationHandlerMapping和一个AnnotationMethodHandlerAdapter实例。<mvc:annotation-driven/>配置能够帮我们省去DefaultAnnotationHandlerMapping和AnnotationMethodHandlerAdapter的声明配置。同时,还提供了数据绑定支持,@NumberFormatannotation支持,@DateTimeFormat支持,@Valid支持,读写XML的支持(JAXB),读写JSON的支持(Jackson)。
(2)拦截器
新建一个拦截器
/**
 * @Description: 实现了HandlerInterceptor接口的自定义拦截器类
 */
public class CustomeInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o)
            throws Exception {
        System.out.println("CustomInterceptor....preHandle");
        return true;
    }
    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView)
            throws Exception {
        System.out.println("CustomInterceptor....postHandle");
    }
    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e)
            throws Exception {
        System.out.println("CustomInterceptor....afterCompletion");
    }
}
 <mvc:interceptors>
                 <mvc:mapping path="/hello"/>
        <bean class="com.ma.interceptor.CustomeInterceptor" />  
 </mvc:interceptors>
 
2、springIOC
springIOC(控制反转)也叫DI(依赖注入),把创建程序的主动权由自己把控转移到由spring容器控制,从而达到解耦的效果。比如当如果依赖的类修改了,如果没有依赖注入,则需要修改依赖对象调用者;再比如敲代码从前端往后台写时会有不能创建未定义类的场景。
依赖注入的方式:
(1)属性注入
 <bean class="com.baobaotao.anno.LogonService">
       <property name="logDao" ref="logDao"></property>
       <property name="userDao" ref="userDao"></property>
 </bean>
(2)构造函数注入
<bean class="com.baobaotao.anno.LogonService">
      <constructor-arg  ref="logDao"></constructor-arg>
       <constructor-arg ref="userDao"></constructor-arg>
</bean>
(3)工厂方式注入
 <bean id="car5" factory-bean="carFactory" factory-method="createHongQiCar"/>
springIOC的注解
@Component是所有受Spring 管理组件的通用形式,一般用于实体类。
@Controller控制层注解。
@ Service服务层注解。
@ Repository dao层注解。
@Autowired自动装配,只按照byType注入。默认情况下它要求依赖对象必须存在,如果允许null值,可以设置它的required属性为false。如果我们想使用按照名称(byName)来装配,可以结合@Qualifier注解一起使用。
@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。所以,如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。如果既不制定name也不制定type属性,这时将通过反射机制使用byName自动注入策略。
@Value。
3、springAOP
AOP:面向切面编程,在调用方法的前后处理某类公共事务,比如写日志、事务、权限判断等,Struts2的拦截器设计就是基于AOP的思想。Spring默认使用JDK动态代理,在需要代理类而不是代理接口的时候,Spring会自动切换为使用CGLIB代理。
(1)动态代理
JDK动态代理:通过反射类Proxy和InvocationHandler回调接口实现。

CGLIB动态代理:采用asm字节码生成框架生成代理类的字节码。
Enhancer enhancer = new Enhancer();  
enhancer.setSuperclass(UserServiceImpl.class);  
enhancer.setCallback(new MyMethodInterceptor()); //代理类需要实现MethodInterceptor接口
UserServiceImpl userService = (UserServiceImpl)enhancer.create();
(2)AOP基本概念(点、线、面)
横切关注点:对哪些方法进行拦截,拦截后怎么处理,这些关注点称之为横切关注点。
JointPoint(连接点):程序执行过程中明确的点,一般是方法的调用。
Pointcut(切入点):连接点集合,在程序中主要体现为定义连接点的表达式。
Advice(通知):AOP在特定的切入点上执行的增强处理,有before,after,afterReturning,afterThrowing,around
Aspect(切面):通常是一个类,里面可以定义切入点和通知。

weave(织入):将切面应用到目标对象并导致代理对象创建的过程。
(3)配置
             <aop:config>
            <aop:aspect id="time" ref="timeHandler">
                <aop:pointcut id="addAllMethod" expression="execution(* com.xrq.aop.HelloWorld.*(..))" />
                <aop:before method="printTime" pointcut-ref="addAllMethod" />
                <aop:after method="printTime" pointcut-ref="addAllMethod" />
            </aop:aspect>
        </aop:config>
(4)通知
前置通知[Before]:前置通知不会影响连接点的执行,除非此处抛出异常,可以通过arg-names="name,age"传递参数。 
正常返回通知[after-returning]:在连接点正常执行完成后执行,如果连接点抛出异常,则不会执行。可以通过returning="name"获取返回参数。 
异常返回通知[after-throwing]:在连接点抛出异常后执行。 
返回通知[After]:不管是正常执行完成,还是抛出异常,都会执行返回通知中的内容。 
环绕通知[Around]:环绕通知围绕在连接点前后,比如一个方法调用的前后。这是最强大的通知类型,能在方法调用前后自定义一些操作。环绕通知还需要负责决定是继续处理join point(调用ProceedingJoinPoint的proceed方法)还是中断执行。 4、定时任务
(1)注解式
添加task扫描注解
        <task:annotation-driven scheduler="taskid" mode="proxy"/>  
        <task:scheduler id="taskid" />  
在定时执行的方法上添加注解
    @Scheduled(cron = "0/5 * * * * ?")
    public void task(){
        System.out.println("定时任务");
    }
(2)配置
        <task:annotation-driven />
        <bean id="taskclass" class="com.Taskclass"></bean>
    <task:scheduled-tasks>
        <task:scheduled ref="taskclass" method="method" cron="0/5 * * * * ?" />
    </task:scheduled-tasks>
(3)时间定义
一个cronExpression表达式有至少6个(也可能是7个,最后一位年可选)由空格分隔的时间元素。从左至右秒、分、时、日月、星期、年。星期不能和详细日期同时出现。
符号:
,多次任务。如 在26分、29分、33分执行一次:0 26,29,33 * * * ?
/循环任务,表示每多久执行一次。如每隔5分执行一次:0 */5 * * * ?
-范围,如没小时的0到5分钟每分钟执行一次:0 0-5 14 * * ?
“L”字符:用在日表示一个月中的最后一天,用在周表示该周最后一个星期,也就是周日。
“?”字符:表示不确定的值。只能用在“月”和“周”两个域。

三、源码篇

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值