java注解如何配置
注解的基本配置方法
在Java中,注解通过@interface关键字定义,可以包含成员变量和默认值。以下是一个简单注解的配置示例:
public @interface MyAnnotation {
String value() default "default";
int count() default 1;
}
元注解的使用
元注解用于修饰其他注解,控制注解的行为:
@Target(ElementType.METHOD) // 指定注解可用于方法
@Retention(RetentionPolicy.RUNTIME) // 注解在运行时保留
public @interface Loggable {
boolean enabled() default true;
}
注解参数配置
注解可以包含多种类型的参数,包括基本类型、字符串、枚举、Class对象、其他注解或数组:
public @interface ComplexAnnotation {
String[] tags();
Class<?> targetClass();
RetentionPolicy retention() default RetentionPolicy.CLASS;
}
配置注解处理器
处理运行时注解通常需要反射API:
Method method = obj.getClass().getMethod("methodName");
if (method.isAnnotationPresent(MyAnnotation.class)) {
MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
System.out.println(annotation.value());
}
编译时注解处理
对于编译时处理的注解,需要实现AbstractProcessor:
@SupportedAnnotationTypes("com.example.MyAnnotation")
@SupportedSourceVersion(SourceVersion.RELEASE_8)
public class MyAnnotationProcessor extends AbstractProcessor {
@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment roundEnv) {
// 处理逻辑
return true;
}
}
Spring框架中的注解配置
在Spring中,注解常用于依赖注入和配置:
@Configuration
@ComponentScan("com.example")
@PropertySource("classpath:app.properties")
public class AppConfig {
@Bean
public MyService myService() {
return new MyServiceImpl();
}
}
Lombok注解示例
Lombok通过注解简化代码:

@Data
@AllArgsConstructor
public class User {
private String name;
private int age;
}
每种注解配置方式适用于不同场景,根据具体需求选择合适的注解类型和配置方法。运行时注解提供灵活性但可能影响性能,编译时注解更高效但需要额外处理工具。






