注解

注解:
如何理解注解(Annotation)

1)JDK1.5推出的新特性
2)JAVA中的一种元数据(描述数据的数据,类似xml)
3)JAVA中的一种特殊的class(注解最终会编译成.clss文件)

注解的应用场景
1)描述类及其成员(属性,方法)
2)替换项目中xml放在对相关对象的描述
例如:spring框架中的相关注解

注解描述
@Configuration描述配置类对象
@Service描述业务层对象
@controller描述控制层对象
@Responsitory描述数据层对象
@ RestControllerAdvice描述控制全局的异常处理
@Bean描述bean对象,一般修饰方法将返回值交给spring管理
@Autowired实现bean对象的自动装配

注解的定义
借助@interface关键字进行定义

@Retention 用于描述注解何时有效
RetentionPolicy.RUNTIME 指运行时有效
RetentionPolicy.SOURCE 指编译时有效

说明:自定义注解包括框架的很多注解都是运行时有效,在运行时可以通过反射技术获取这些注解
并给予注解的描述,实现相关的操作

@Target用于描述注解可以修饰的对象(类,属性,方法)
ElementType.METHOD 指修饰方法
ElementType.TYPE 指修饰类
ElementType.EIELD 指修饰属性

注解应用案例分析实现
1)与编译器结合使用
2)与发射API结合使用

例如:通过反射获取类上的注解及属性或方法

package annotation;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Field;



/**自定义注解
 * 通过反射获取类上的注解*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Controller{
	String value() default "";
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@interface Service{
	String value() default "";
}

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
@interface Autowired{
	
}

@Service
class SysLogService{
	
}

@Controller("logController")
class SysLogController{
	@Autowired
	private SysLogService sysLogService;
}

public class TestAnnotation01 {
	public static void main(String[] args) throws Exception {
		//获取类上的注解
		Class<?> cls = Class.forName("annotation.SysLogController");//包名.类名
		boolean flag = cls.isAnnotationPresent(Controller.class);
		System.out.println(flag);
		//获取注解的参数值
		Controller con = cls.getDeclaredAnnotation(Controller.class);
		System.out.println(con.value());
		
		//获取类中的属性
		Field[] fs=cls.getDeclaredFields();
		for (Field f : fs) {
			if(f.isAnnotationPresent(Autowired.class)){
				System.out.println("执行DI操作");
			}
		}
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值