博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Spring Annotation知识梳理
阅读量:7211 次
发布时间:2019-06-29

本文共 5757 字,大约阅读时间需要 19 分钟。

hot3.png

Spring annotation:(目的:减少applicationContext.xml文件配置)
使用注解时需要添加扫描包操作:(context命名空间)

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

一.IOC注解:
@Component    表示将该类配置到IOC容器中,替代bean的配置
        --   表示为Action层的Bean
        --       表示为Service层的bean
        --  表示为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;

    }

  }

转载于:https://my.oschina.net/u/3676262/blog/1552880

你可能感兴趣的文章
play2.0实现新浪OAuth2.0
查看>>
QT:使用“状态模式”绘制界面 参考的一种面向对象的绘制图片的方法
查看>>
for 循环 里面 save 的问题
查看>>
常用 arm 汇编指令
查看>>
如何用_R_语言的_Shiny_库编写_web_程序
查看>>
mysql初步入门
查看>>
你对C++语言的理解到了哪一步呢
查看>>
JEECMS中FreeMarker的Macro
查看>>
高性能JavaScript(您值得一看)
查看>>
工作记录
查看>>
MySQL修改默认字符集
查看>>
HTTP Keep-Alive是什么?如何工作?
查看>>
maven 异常解决
查看>>
实现林间的选择性身份验证
查看>>
进程的调度算法
查看>>
使用elasticsearch1.5.2实现查找附近的人
查看>>
SQL SERVER 批量将修改字段名为大、小写
查看>>
#ifdef __cplusplus extern C{}与C和C++间的关系
查看>>
lvs的nat模式实验
查看>>
利用ftp服务器实现无人值守的安装
查看>>