Spring Annotation知识梳理

 2023-09-13 阅读 28 评论 0

摘要:2019独角兽企业重金招聘Python工程师标准>>> Spring annotation:(目的:减少applicationContext.xml文件配置) 使用注解时需要添加扫描包操作:(context命名空间) <context:component-scanbase-package=""></context:component-scan> 一.IOC注

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

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方法调不到.
示例:

Spring原理。@Component(value="u")

publicclass User {

@Value("${user}")

Springboot注解、private Stringusername;

@Value("${password}")

private Stringpassword;

Spring详解,}

@Component                         //将该类配置到IOC容器中,代替bean的配置

@Scope(value="prototype")  //多例配置,默认是单例的

Spring揭秘,publicclass SpringBean {

@Value(value ="127")

privatebyte b;

Springboot常用注解,@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

版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/1/54656.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息