public class MyService {
@MyAnnotation(value = "测试方法", level = 2)
public void doSomething() {
System.out.println("执行doSomething方法");
}
}
✅ 3. 使用反射解析注解
csharp复制代码
public class AnnotationProcessor {
public static void process(Object obj) throws Exception {
for (Method method : obj.getClass().getDeclaredMethods()) {
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation anno = method.getAnnotation(MyAnnotation.class);
System.out.println("方法名:" + method.getName());
System.out.println("注解值:value=" + anno.value() + ", level=" + anno.level());
method.invoke(obj); // 调用带注解的方法
}
}
}
}
🧩 四、注解的三大核心属性
属性
描述
@Target
指定注解可以作用的目标(类、方法、字段等)
@Retention
指定注解的生命周期(源码期、编译期、运行时)
@Documented
是否被 Javadoc 工具记录
@Inherited
子类是否继承父类的注解
@Repeatable
是否允许注解重复使用(JDK 8+)
🧪 五、Java 注解在主流框架中的应用
✅ 1. Spring 框架(依赖注入、MVC、事务管理)
kotlin复制代码
@Component
public class UserService {
@Autowired
private UserRepository userRepo;
@GetMapping("/users")
public List<User> getAllUsers() {
return userRepo.findAll();
}
}
✅ 2. Lombok(自动生成 getter/setter/toString)
less复制代码
@Data // 自动生成 getter、setter、equals、hashCode、toString
@NoArgsConstructor
@AllArgsConstructor
public class User {
private Long id;
private String name;
}
✅ 3. MyBatis(SQL 映射、参数绑定)
kotlin复制代码
@Mapper
public interface UserMapper {
@Select("SELECT * FROM users WHERE id = #{id}")
User selectById(Long id);
}
✅ 4. Swagger(API 文档生成)
less复制代码
@RestController
@Api(tags = "用户管理接口")
public class UserController {
@GetMapping("/users")
@ApiOperation("获取所有用户")
public List<User> getAllUsers() {
return userService.findAll();
}
}