您的位置:首页 > 编程语言 > Java开发

Spring Annotation知识梳理

2017-07-26 14:38 148 查看
Spring annotation:(目的:减少applicationContext.xml文件配置)
使用注解时需要添加扫描包操作:(context命名空间)

<context:component-scanbase-package=""></context:component-scan>

一.IOC注解:
@Component    表示将该类配置到IOC容器中,替代bean的配置
        --@Controller   表示为Action层的Bean
        --@Service       表示为Service层的bean
        --@Repository  表示为Dao层的bean
以上三类实质都是@Component,在确定是哪层bean时使用响应注解.
***** 注:1.使用以上注解,默认bean的名称为类名首字母小写
        2.若要改变bean的名称可使用自定bean的名称@Component(value="springB")
(1)简单值装配:使用@Value(value="值")  括号内只有一个值时括号内的value可省略  
(2)其他bean的引用: 使用自动装配
@Autowired  根据byName和ByType装配,只要由一个可以装配就成功
可以结合@Qualifier(value="u1")  手工定义需要装配的bean的名称
(3)集合:需要结合util的命名空间
类中使用:@javax.annotation.Resource 配置文件中使用<util:list id="">等 
(4)初始化方法/销毁方法分别使用@PostConstruct和@PreDestroy
@Scope 通过该注解配置bean域(类别).默认是单例的,多例中,bean不会放在容器中,destroy方法调不到.
示例:

@Component(value="u")
publicclass User {

@Value("${user}")
private Stringusername;
@Value("${password}")
private Stringpassword;

}
@Component                         //将该类配置到IOC容器中,代替bean的配置
@Scope(value="prototype")  //多例配置,默认是单例的
publicclass SpringBean {

@Value(value ="127")

privatebyte
b;

@Value(value ="3333")

private Shorts;

@Value(value ="a")

private Characterc;

@Value("java.lang.String")
private Classclazz;
@Value("classpath:applicationContext.xml")
private Resourceresource;
@Value("string")
private Stringstr;

@Autowired
@Qualifier(value ="u")
private Useruser;
@Resource
private Integer[]ints;

@Resource(name ="users")
private List<User>lists;
@Resource
private Set<User>sets;
@Resource
private Map<Long, User>maps;
@Resource
private Propertiesproperties;

@PostConstruct
publicvoid init() {

System.out.println("SpringBean.init()");

}

@PreDestroy
publicvoid destory() {

System.out.println("SpringBean.destory()");

}

}

applicationContext.xml配置:
<!-- 加载配置文件 -->
//方法一:

<!--<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

      <propertyname="location"value="classpath:ioc/info.properties"></property>

    </bean>-->

方法二:

<context:property-placeholderlocation="classpath:ioc/info.properties"/>

<beanid="u1"class="ioc.User">    
//u1手动赋值

<propertyname="username"value="admin1"></property>

<propertyname="password"value="nnnnn"></property>

</bean>

<util:listid="ints">

<value>12</value>

<value>13</value>

</util:list>

<util:listid="users">

<refbean="u"/>  //u从配置文件读取信息注入

<refbean="u1"/> //u1手动赋值注入

</util:list>
<util:setid="sets">

<refbean="u"/>

<refbean="u1"/>

<beanclass="ioc.User">

<propertyname="username"value="admin2"></property>

<propertyname="password"value="1233333"></property>

</bean>

</util:set>
<util:mapid="maps">

<entrykey="1"value-ref="u"></entry>

<entrykey="2"value-ref="u1"></entry>

</util:map>
<util:propertiesid="properties">

<propkey="key1">value1</prop>

<propkey="key2">value2</prop>

</util:properties>

  ***** 读取配置文件:
方式一: 使用后处理器,PropertyPlaceholderConfigurer类

<beanclass="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

<propertyname="location"value="classpath:ioc/info.properties"></property>

</bean>

方式二:采用aop命名空间(需加入aop Schama约束文件)

<context:property-placeholderlocation="classpath:ioc/info.properties"/>

二.AOP注解: (配置与使用命名空间类似)
1.配置target 容器中扫描该类可获取类名首字母小写的目标类的实例bean

@Service
publicclass LoginServiceImplimplements LoginService{}

<!--
扫描包 -->
<context:component-scanbase-package="aop"></context:component-scan>

配置Target   使用ioc注解  给target添加,扫描包
2.配置Advice   使用ioc注解  给advice添加,扫描包

3.织入
a.配置pointcut   

可以在advice中添加空方法使用注解@Pointcut("AspectJ表达式")   id就是方法名称

@Pointcut(value="execution(* aop.impl.*ServiceImpl.*(..))")

publicvoid  pointcut(){}

b.给Advice添加注解@Aspect(类级别)  表示该advice为一个切面

@Aspect

publicclass  LogAdvice{}

c.给方法添加以下注解,表示通知类型

@Before("pointcut的方法名")//前置通知

@AfterReturning(pointcut="pointcut的方法名",returning="变量名称")//后置通知

@AfterThrowing(pointcut="pointcut的方法名",throwing="变量名称")  //异常通知

@Around("pointcut的方法名")//环绕通知

4.解析AspectJ注解
方式一: 使用spring提供类AnnotationAwareAspectJAutoProxyCreator

<beanclass="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"></bean>

方式二:采用aop命名空间

<aop:aspectj-autoproxy/>

advice配置示例:

  //2.配置Advice
  @Component
  //表示该advice是一个切面
  @Aspect
  publicclass LogAdvice {
    //3.切点配置,添加空的方法并如下配置(连接点的具体实现)
    @Pointcut(value="execution(* aop.impl.*ServiceImpl.*(..))")
    publicvoid pointcut(){}
    //前置通知,并指定连接点(空方法的方法名)
    @Before(value="pointcut()")
    publicvoid log() {

System.out.println("LogAdvice.log()");

    }

    publicvoid log1(JoinPointjoinpoint) {
      Objecttarget = joinpoint.getThis();
      StringmethodName = joinpoint.getSignature().getName();
      Object[]args = joinpoint.getArgs();
      System.out.println("methodName:"+ methodName +"  args:" +
Arrays.toString(args) +" target:" + target);
    }
    //后置通知,需加返回值returning
  @AfterReturning(pointcut="pointcut()",returning="returnValue")
    publicvoid afterReturning(JoinPointjoinpoint, Object returnValue) {
      Objecttarget = joinpoint.getThis();
      StringmethodName = joinpoint.getSignature().getName();
      Object[]args = joinpoint.getArgs();
      System.out.println("methodName:"+ methodName +"  args:" +
Arrays.toString(args) +" target:" + target +"returnValue:" + returnValue);
    }
    //异常通知,需加throwing
    @AfterThrowing(pointcut="pointcut()",throwing="ex")
    publicvoid afterThrowing(JoinPointjoinpoint, Exception ex) {
      Objecttarget = joinpoint.getThis();
      StringmethodName = joinpoint.getSignature().getName();
      Object[]args = joinpoint.getArgs();
      System.out.println("methodName:"+ methodName +"  args:" +
Arrays.toString(args) +" target:" + target +" ex:" + ex);
    }
    //环绕通知
    @Around("pointcut()")
    public Object time(ProceedingJoinPointjoinPoint)throwsThrowable {
      Objecttarget = joinPoint.getThis();
      StringmethodName = joinPoint.getSignature().getName();
      Object[]args = joinPoint.getArgs();
      long startTime = System.currentTimeMillis();
      ObjectreturnValue = joinPoint.proceed();
      long endTime = System.currentTimeMillis();
      System.out.println(methodName +" cost "+ (endTime - startTime) + "ms.");
      return returnValue;
    }
  }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: