Annotation(注解)概述

从JDK5.0开始, Java增加了对元数据(MetaData)的支持,也就是 Annotation(注解)。 
Annotation其实就是代码里的特殊标记,它用于替代配置文件,也就是说,传统方式通过配置文件告诉类如何运行,有了注解技术后,开发人员可以通过注解告诉类如何运行。在Java技术里注解的典型应用是:可以通过反射技术去得到类里面的注解,以决定怎么去运行类。

1.自定义一个注解:

@Target({ElementType.TYPE,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnotation {
String temp() default "";
}

(1).@Retention– 定义该注解的生命周期
  RetentionPolicy.SOURCE : 在编译阶段丢弃。这些注解在编译结束之后就不再有任何意义,所以它们不会写入字节码。@Override, @SuppressWarnings都属于这类注解。
  RetentionPolicy.CLASS : 在类加载的时候丢弃。在字节码文件的处理中有用。注解默认使用这种方式
  RetentionPolicy.RUNTIME : 始终不会丢弃,运行期也保留该注解,因此可以使用反射机制读取该注解的信息。我们自定义的注解通常使用这种方式。

(2).@Target – 表示该注解用于什么地方。默认值为任何元素,表示该注解用于什么地方。可用的ElementType参数包括
  ElementType.CONSTRUCTOR:用于描述构造器
  ElementType.FIELD:成员变量、对象、属性(包括enum实例)
  ElementType.LOCAL_VARIABLE:用于描述局部变量
  ElementType.METHOD:用于描述方法
  ElementType.PACKAGE:用于描述包
  ElementType.PARAMETER:用于描述参数
  ElementType.TYPE:用于描述类、接口(包括注解类型) 或enum声明

2.Spring使用注解。

在Spring核心配置文件配置:

 <context:component-scan base-package="cn.*"/> <!-- 扫描cn包下的所有Bean -->
<context:component-scan base-package="cn.pojo,cn.test"/> <!-- 扫描指定包下的Bean,用逗号隔开 -->

如果扫描到的类上带有特定的注解(以下注解),这个对象就会交给Spring容器管理。

@Component:是所有受Spring容器管理的通用组件形式,可以放在类头上,并不推荐使用。

   @Component("userDao")//这里通过注解定义了一个DAO
public class UserDaoImp implements IUserDao {
@Override
public int addUser(User user) {
//这里并未实现数据库操作,仅作为说明问题
System.out.println("新增用户操作");
return 0;
}
}

@Repository:用于标注DAO类。

 @Repository("userDao")
public class UserDaoImp implements IUserDao {
@Override
public int addUser(User user) {
System.out.println("新增用户操作");
return 0;
}
}

在数据访问层使用此标注userdao类,然后在业务逻辑层实现注解的注入。

     @Resource(name="userDao")

     @Autowired
@Qualifier("userDao")
private IUserDao userDao;

JDK提供的注解:@Resource:根据name指定相应的dao类进行注入到userDao属性。

Spring框架内部提供的注解:@Autowired:根据type进行自动装载,可配合@Qualifier注解根据name值进行注入。

  1.@Autowired也可以对方法进行入参进行注入:

     private IUserDao userDao;

     @Autowired
public void setUserDao(@Qualifier("userDao")IUserDao userDao) {
this.userDao = userDao;
}

  2.使用@autowired注解进行装配时,如果找不到相匹配的Bean组件,Spring容器会抛出异常。如果依赖不是必须的,则可以将required的属性的设置为false。默认是为true的,即必须找到相匹配的Bean完成装配,否则就抛出一个异常。

     private IUserDao userDao;

     @Autowired(required = false)
public void setUserDao(@Qualifier("userDao")IUserDao userDao) {
this.userDao = userDao;
}

  3.如果对类中集合类型的成员变量或方法入参使用@autowired注解,Spring会将容器中所有和集合中的元素类型进行匹配的Bean组件都注入进来。

      @Autowired(required = false)
private List<User> list;//Spring容器会将User类型的Bean组件都注入给list属性。

@Service:用于标注业务类。

  @Service("userService")
public class UserServiceImp implements IUserService {
@Resource(name="userDao")
private IUserDao userDao; @Override
public int addUser(User user) {
return userDao.addUser(user);
}
}

@Service("userService")注解是告诉Spring,当Spring要创建UserServiceImpl的实例时,bean的名字必须叫做“userService”,这样当Action需要使用UserServiceImpl的实例时,
就可以由Spring创建好的“userService”然后注入给Action:在Action只需要声明一个名字叫“userService”的变量来接收由Spring注入的“userService”。

@Controller:用来标注控制器类,也就是Action。

使用注解定义切面
AspectJ:是一个面向切面的框架,扩展了Java语言,定义了AOP语法,能够在编译期提供代码的织入,所有它拥有一个专门的编译器用来生成遵守字节编码的规范Class文件。
@AspectJ是AspectJ 5新增的功能,使用JDK 5.0注解技术和正规的切点表达式语言描述切面。所以在使用之前,需要保证JDK版本是5.0以上版本,否则无法使用。

  1.使用注解标注切面

 package cn.advice;

 import org.apache.log4j.Logger;
import org.aspectj.lang.JoinPoint;
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;
import org.springframework.stereotype.Component; @Component("serviceAdvice")
@Aspect
public class ServiceLoggingAdvice {
private Logger logger = Logger.getLogger(ServiceLoggingAdvice.class);
//定义切入点---可使用模糊查询进行匹配
@Pointcut("execution(* cn.dao..*.*(..))")
public void pointcut(){}
//标注前置增强
@Before(value = "pointcut()")
public void before(JoinPoint joinPoint){
String methodName = joinPoint.getSignature().getName();//获得目标方法名
String className = joinPoint.getTarget().getClass().getSimpleName();//获得目标方法的类名
logger.info("前置增强...."); }
//后置增强
@AfterReturning(pointcut="pointcut()")
public void after(JoinPoint joinPoint){
logger.info("后置增强....");
}
//异常抛出增强
@AfterThrowing(pointcut = "pointcut()",throwing = "e")
public void afterThrowing(JoinPoint joinPoint,Exception e){
String exeMessage = e.getMessage();
logger.info(exeMessage);
}
//后置增强
@After("pointcut()")
public void afterEnd(JoinPoint joinPoint){
logger.info("最终增强....");
}
//环绕增强
@Around("execution(* cn.service..*.*(..))")
public Object round(ProceedingJoinPoint joinPoint){
Object result = null;
try {
logger.info("环绕增强 ------前面。。"); result = joinPoint.proceed();//此方法调用真正的目标方法,从而实现对连接点的完全控制。 logger.info("环绕增强 ------后面。。");
} catch (Throwable e) {
e.printStackTrace();
}
return result;
}
}

  2.在核心XML配置文件

    (1)首先导入aop命名空间

 <?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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
</beans>

    (2)在核心配置文件里加入<aop:aspectj-autoproxy />元素,就可以启用对于@AspectJ注解的支持,Spring会自动为匹配的Bean创建代理。

小结:

1、被注解的java类当做Bean实例,Bean实例的名称默认是Bean类的首字母小写,其他部分不变。@Service也可以自定义Bean名称,但是必须是唯一的!

2、尽量使用对应组件注解的类替换@Component注解,在spring未来的版本中,@Controller,@Service,@Repository会携带更多语义。并且便于开发和维护!

Spring的注解问题的更多相关文章

  1. Spring MVC注解的一些案列

    1.  spring MVC-annotation(注解)的配置文件ApplicationContext.xml <?xml version="1.0" encoding=& ...

  2. Spring系列之Spring常用注解总结

    传统的Spring做法是使用.xml文件来对bean进行注入或者是配置aop.事物,这么做有两个缺点:1.如果所有的内容都配置在.xml文件中,那么.xml文件将会十分庞大:如果按需求分开.xml文件 ...

  3. spring @condition 注解

    spring @condition注解是用来在不同条件下注入不同实现的 demo如下: package com.foreveross.service.weixin.test.condition; im ...

  4. spring mvc(注解)上传文件的简单例子

    spring mvc(注解)上传文件的简单例子,这有几个需要注意的地方1.form的enctype=”multipart/form-data” 这个是上传文件必须的2.applicationConte ...

  5. Spring的注解方式实现AOP

    Spring对AOP的实现提供了很好的支持.下面我们就使用Spring的注解来完成AOP做一个例子. 首先,为了使用Spring的AOP注解功能,必须导入如下几个包.aspectjrt.jar,asp ...

  6. Spring 之注解事务 @Transactional

    众所周知的ACID属性:  原子性(atomicity).一致性(consistency).隔离性(isolation)以及持久性(durability).我们无法控制一致性.原子性以及持久性,但可以 ...

  7. 数据库事务中的隔离级别和锁+spring Transactional注解

    数据库事务中的隔离级别和锁 数据库事务在后端开发中占非常重要的地位,如何确保数据读取的正确性.安全性也是我们需要研究的问题.ACID首先总结一下数据库事务正确执行的四个要素(ACID): 原子性(At ...

  8. Spring JSR-250注解

    Java EE5中引入了“Java平台的公共注解(Common Annotations for the Java Platform)”,而且该公共注解从Java SE 6一开始就被包含其中. 2006 ...

  9. 【SSM 2】spring常用注解

    声明:以下观点,纯依据个人目前的经验和理解,有不当之处,多指教! 一.基本概述 注解(Annotation):也叫元数据.一种代码级别的说明.它是JDK1.5及以后版本引入的一个特性,与类.接口.枚举 ...

  10. atititt.java定时任务框架选型Spring Quartz 注解总结

    atititt.java定时任务框架选型Spring Quartz 总结 1. .Spring Quartz  (ati recomm) 1 2. Spring Quartz具体配置 2 2.1. 增 ...

随机推荐

  1. WCF研究-中篇

    中篇 5.托管于宿主 6.消息模式 7.WCF行为-实例管理和并发控制 8.安全 5.托管于宿主 托管 宿主Host Ø承载WCF Service运行的环境 自承载方式 系统服务方式 IIS方式 WA ...

  2. JavaWeb实现上传文件

    需要 commons-io与commons-fileupload 首先在jsp中创建一下布局 <%@ page contentType="text/html;charset=UTF-8 ...

  3. MFC 中 Tooltip 实现的几种方式

    方法一:利用CWnd本身自身支持的tooptip来实现,这种方法适用给控件增加tooltip,非常方便和简单方法如下:1.在窗口中增加消息映射ON_NOTIFY_EX(TTN_NEEDTEXT, 0, ...

  4. python合并多个文件

    import os filelist=os.listdir('/root/Music') for item in filelist: print item newfile=open('/root/Mu ...

  5. 使用 Gitlab CI/CD 实现自动化发布站点到 IIS

    说明 这里先介绍下两个东西 CI/CD.GitLab Runner,当然在此之前你需要对 git 有所了解,关于 git 这里不做说明,可以自行百度. 首先介绍 CI/CD :随着我们开发方式的转变, ...

  6. 血的教训--如何正确使用线程池submit和execute方法

    血的教训之背景:使用线程池对存量数据进行迁移,但是总有一批数据迁移失败,无异常日志打印 凶案起因 ​ 听说parallelStream并行流是个好东西,由于日常开发stream串行流的场景比较多,这次 ...

  7. Zookeeper详解-应用程序(七)

    Zookeeper为分布式环境提供灵活的协调基础架构.ZooKeeper框架支持许多当今最好的工业应用程序.我们将在本章中讨论ZooKeeper的一些最显着的应用. 雅虎 ZooKeeper框架最初是 ...

  8. Python自学day-7

    一.静态方法(@staticmethod) class Dog(object): def __init__(self): pass @staticmethod def talk(): #静态方法 pa ...

  9. Electron为文件浏览器创建图标(三)

    在前面的文章中,请看之前文章,我们已经完成了使用 electron做文件浏览器这么一个应用,现在我们需要为应用创建图标操作.为应用创建图标以后,我们就可以从计算机中与其他应用区分开来,如果我们自己会做 ...

  10. Element-ui安装之MessageBox详解

    1.首先根据官方文档进行Element-ui的安装,这个过程很简单(通过webpack-simple) 1) vue init webpack-simple element-ui 2) cd elem ...