Spring 笔记总结

时间:2023-03-09 08:51:30
Spring 笔记总结

1、Spring框架的核心是提供一个容器(BeanFactory 或 ApplicationContext),提供以下功能:

  1)创建和销毁组件对象,类似“工厂类”

  2)采用不同的模式创建对象

  3)IOC

  4)AOP

2、Bean组件配置

  <bean id="标识符" class="完整类路径" scope="type" init-method="方法名" destroy-method="方法名"/>

    type:1)singleton:单例模式,在容器实例化时创建

       2)prototype:在调用getBean()时创建

    指定销毁方法是在容器关闭时触发,只适用于singleton

  使用时:

    ApplicationContext ac = new ClassPathXmlApplicationContext("path/of/applicationContext.xml");

    Bean bean = (Bean)ac.getBean("beanid");

3、Spring IOC(Inverse of Controller)

  将对象关系的指定,对象创建,初始化和销毁等逻辑交给Spring负责

4、DI(Dependency Injection)

  Spring采用DI技术实现IOC控制思想

  注入的两种方法:

    1)setter方式注入,使用set方法注入,在<bean>中采用如下描述:

      <property name="属性名" ref="注入Bean对象的ID" />

    2)构造方法注入,提供构造方法注入,少用,<bean>中配置:

      <constructor-arg index ="参数索引,从0开始计数" ref="注入Bean对象的ID" />

  Spring中各种类型的数据注入

    1)Bean对象注入

      <property name="属性名" ref="注入Bean对象的ID" />

    2)基本数据的注入

      <property name="属性名" value="值" />

    3)集合的注入

      (1)List Set  

        <property name="属性名" >

          <list>

            <value>value0</value>

            <value>value1</value>

          </list>

        </property>

      <!-- 普通值用<value>标签,对象用<bean>标签:<ref bean="beanid" />,如果是集合,<list> 标签改成 <set> -->

      (2)Map     

        <property name="属性名" >

          <map>

            <entry key="键0" value="值0" />

            <entry key="键1" value="值1" />

          </map>

        </property>

      <!-- 普通值用<value>标签,对象用: <entry key="键0" value-ref="beanid" />-->

      (3)properties

        <property name="属性名" >

          <props>

            <prop key="键0"> value<prop/>

            <prop key="键1"> value<prop/>

          </props>

        </property>

5、AOP(Aspect Orented Programming)

  1)aspect:插入的通用处理功能组件

  2)joinpoint:连接点,aspect插入点

  3)pointcut:joinpoint组成pointcut

  4)advice:通知,aspect 和 joinpoint间的发生次序

  5)target:目标,利用切入点指定的组件和方法

  6)autoproxy:AOP利用动态代理实现AOP

  例子:

   <aop:config>
        <aop:aspect id="TestAspect" ref="aspectBean">
            <!--配置com.spring.service包下所有类或接口的所有方法-->
            <aop:pointcut id="businessService" expression="execution(* com.spring.service.*.*(..))" />
            <aop:before pointcut-ref="businessService" method="doBefore"/>
            <aop:after pointcut-ref="businessService" method="doAfter"/>
            <aop:around pointcut-ref="businessService" method="doAround"/>
            <aop:after-throwing pointcut-ref="businessService" method="doThrowing" throwing="ex"/>
        </aop:aspect>
    </aop:config>  

    <bean id="aspectBean" class="com.spring.aop.TestAspect" />
    <bean id="aService" class="com.spring.service.AServiceImpl"></bean>
    <bean id="bService" class="com.spring.service.BServiceImpl"></bean>  

  切入点定义:

    1)方法限定表达式:execution(修饰符(可无) 返回类型 方法名(参数列表)  异常(可无))

    2)类型限定表达式:with(类型)

    3)Bean名称限定:Bean(id)

    4)args参数限定:args(类型)

6、log4j

  log4j主要有以下3部分构成

    1)日志器(logger)

    2)输出器(appender)

    3)布局器(格式器,layout)

  如:

#1. 设置输出级别
log4j.rootLogger=info,myconsole,myfile,dateFile,MAIL

#2. 设置具体的配置信息
log4j.appender.myconsole=org.apache.log4j.ConsoleAppender
log4j.appender.myconsole.target=System.out
log4j.appender.myconsole.layout=org.apache.log4j.PatternLayout
log4j.appender.myconsole.layout.conversionPattern=%d{yyyy-MM-dd HH\:mm\:ss.SSS} %l %m %n 

#2. 设置具体的配置信息(文件中)
log4j.appender.myfile=org.apache.log4j.FileAppender
log4j.appender.myfile.file=d:/log4j.txt
log4j.appender.myfile.layout=org.apache.log4j.PatternLayout
log4j.appender.myfile.layout.conversionPattern=%d{yyyy-MM-dd HH\:mm\:ss.SSS} %l %m %n

#2. 设置具体的配置信息(文件中,每天一个)
log4j.appender.dateFile=org.apache.log4j.DailyRollingFileAppender
log4j.appender.dateFile.File=d\:/my.html
log4j.appender.dateFile.layout=org.apache.log4j.HTMLLayout
log4j.appender.dateFile.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%c] [%p] - %m%n

#2. 设置具体的配置信息(发送邮件)
log4j.appender.MAIL=org.apache.log4j.net.SMTPAppender
#控制当前级别: log4j.appender.MAIL.Threshold=FATAL
log4j.appender.MAIL.bufferSize=100
log4j.appender.MAIL.From=zuxia@qq.com
log4j.appender.MAIL.SMTPHost=127.0.0.1
log4j.appender.MAIL.Subject=Log4J Message
log4j.appender.MAIL.To=zuxia@qq.com
log4j.appender.MAIL.layout=com.zuxia.test.MyLayoutPattern #此类是用户自定义的哦 重写了HTMLLayout类
log4j.appender.MAIL.layout.ConversionPattern=%d - %c -%-4r [%t] %-5p %c %x - %m%n

  在log4j.properties如果配置多种输出方式,其均有效  

  获取logger时:

    Logger logger = Logger.getLogger(??)

    ??在打印日志的时候会显示出来

7、Spring注解配置

  1)组件扫描: 

    @Component:其他组件

    @Controller:Action组件

    @Service:Service组件

    @Repository:Dao组件

  注解只能用在类定义前,方法定义前,成员变量定义前,上述注解只是推荐用法

  2)开启组件扫描方法:

    <context:component-scan base-package="package.path" />

  4)注入注解,注入标记在成员变量定义前使用

    @Resource:默认按类型匹配注入,如有多个符合要求类型,报错,匹配不唯一,使用名称注入方式

      @Resource(name="beanid")

    @Autowired:默认按类型匹配注入,如有多个符合要求类型,则使用名称注入方式

      @Autowired

      @Qualifier("beanid")

  5)AOP注解

    (1)开启AOP注解

      <aop:aspect-autoproxy />

    (2)使用@component将组件扫描到时Spring容器

    (3)使用@Aspect将组件定义为Aspect组件

    (4)定义方法,在方法前使用@Pointcut定义切入点表达式

    (5)在target前使用@Around,@Before,@AfterReterning,@AfterThrowing,@After

  例子

package com.bird.service;  

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.After;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;  

/**
 * 切面
 * @author Bird
 *
 */
@Aspect
public class MyInterceptor {
    @Pointcut("execution(* com.bird.service.impl.PersonServiceBean.*(..))")
    private void anyMethod(){}//定义一个切入点  

    @Before("anyMethod() && args(name)")
    public void doAccessCheck(String name){
        System.out.println(name);
        System.out.println("前置通知");
    }  

    @AfterReturning("anyMethod()")
    public void doAfter(){
        System.out.println("后置通知");
    }  

    @After("anyMethod()")
    public void after(){
        System.out.println("最终通知");
    }  

    @AfterThrowing("anyMethod()")
    public void doAfterThrow(){
        System.out.println("例外通知");
    }  

    @Around("anyMethod()")
    public Object doBasicProfiling(ProceedingJoinPoint pjp) throws Throwable{
        System.out.println("进入环绕通知");
        Object object = pjp.proceed();//执行该方法
        System.out.println("退出方法");
        return object;
    }
}  

  6)常用注解汇总

@Configuration把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。
@Scope注解 作用域
@Lazy(true) 表示延迟初始化
@Service用于标注业务层组件、
@Controller用于标注控制层组件(如struts中的action)
@Repository用于标注数据访问组件,即DAO组件。
@Component泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注。
@Scope用于指定scope作用域的(用在类上)
@PostConstruct用于指定初始化方法(用在方法上)
@PreDestory用于指定销毁方法(用在方法上)
@DependsOn:定义Bean初始化及销毁时的顺序
@Primary:自动装配时当出现多个Bean候选者时,被注解为@Primary的Bean将作为首选者,否则将抛出异常
@Autowired 默认按类型装配,如果我们想使用按名称装配,可以结合@Qualifier注解一起使用。如下:
@Autowired @Qualifier("personDaoBean") 存在多个实例配合使用
@Resource默认按名称装配,当找不到与名称匹配的bean才会按类型装配。
@PostConstruct 初始化注解
@PreDestroy 摧毁注解 默认 单例  启动就加载
@Async异步方法调用