注解初定义

1.定义

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

@Retention(RetentionPolicy.RUNTIME) //作用时间,是运行时,其他有编译时等
@Target(ElementType.METHOD) //作用的对象,这里是方法,也可以是类和属性,参数
public @interface SampleAnnotation { 
//注解名称是SampleAnnotation,需要用@interface定义注解
//方法
	String value();
}

 2. 使用

public class SampleAnnatationUser {
//这些值会被注解的value方法得到
	@SampleAnnotation("oh my god ,i put a value in it")
	public void use() {
		System.out.println("success,i use");
	}

	public void notUse() {
		System.out.println("fail,i am not use");
	}
}

 3.实现,无反射不注解

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class SampleMain {
	public static void main(String[] args) {
		SampleAnnatationUser sampleAnnatationUser = new SampleAnnatationUser();
		for (Method method : sampleAnnatationUser.getClass().getMethods()) {
			if (method.isAnnotationPresent(SampleAnnotation.class)) {
				try {
					SampleAnnotation  annotation = method.getAnnotation(SampleAnnotation.class);
					System.out.println(annotation.value());
					method.invoke(sampleAnnatationUser, null);
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (InvocationTargetException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

 

 4.结果

oh my god ,i put a value in it
success,i use

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
通过这个例子我们可以对Spring Boot有一个步的了解。Spring Boot是一个用来简化新Spring应用的搭建和开发过程的框架。它的设计目的是提供一个更快更广泛的入门体验。Spring Boot使用了"习惯优于配置"的理念,让项目能够快速运行起来。它集成了许多常用的第三方库的配置,提供了一系列常用的非功能性特征,如嵌入式服务器、安全性、度量等。Spring Boot并不是Spring的替代者,而是为使用Spring做好各种产品级准备的。在这个例子中,我们通过创建一个Spring Boot应用,并实现一个简单的Http请求处理来体验了Spring Boot的结构简单和开发快速的特性。 在这个例子中,我们需要首先进行环境准备,包括安装和配置Maven。然后,我们创建一个Spring Boot应用的核心配置文件application.properties。接下来,我们在项目的同级目录下创建一个controller包,并在这个包中创建一个HelloController类。这个类使用了@RestController注解,表示这是一个控制器类,并且所有的API接口返回的数据都会以Json字符串的形式返回给客户端。在HelloController类中,我们使用@RequestMapping注解定义了一个路径为"/hello"的方法,该方法返回字符串"hello"。 通过这个例子,我们可以快速体验Spring Boot的简化配置和快速开发的特性,以及使用注解定义API接口和处理请求的方法。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值