我见过几个使用自定义注释的例子.例
@SimpleAnnotation
class SampleBean {
@SimpleAnnotation
public String getName() {
return "AAA";
}
public void setName(String name) {
}
public int getHeight() {
return 201;
}
}
@Target( { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@interface SimpleAnnotation {
}
Run Code Online (Sandbox Code Playgroud)
有人能说出我们为什么使用这个吗?
Ral*_*lph 30
Spring支持许多注释"元注释"的概念.(我不确定是否适合所有人.)
这意味着您可以使用弹簧"核心"注释之一构建自己的注释并注释注释.
例如:
@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Service
public @interface MyService {
}
Run Code Online (Sandbox Code Playgroud)
然后你可以使用这个注释而不是@Service
.(顺便说一句:@Service
,@Repository
,@Controller
使用相同的技术从以"继承" @Component
)
大量使用它的一个例子是"继承" @Qualifier
.有关示例和一些解释,请参阅Spring参考章节:3.9.3使用限定符微调基于注释的自动装配(示例@Genre
在本章末尾.)
可以使用该技术完成的一个非常有用的构造是,它使您能够将多个注释组合到(在您的用例中)更多含义.因此,不要在某些类型的每个类中写入相同的两个注释,例如:@Service
和@Qualifiyer("someting")
(org.springframework.beans.factory.annotation.Qualifier).您可以创建使用这两个注释注释的自定义注释,然后在您的bean中仅使用这一个自定义注释.(@See 避免Spring注释代码气味使用Spring 3自定义注释)
如果您想了解这种技术的强大功能,您可以查看Context和Dependency Injection Framework.
评论中的问题:
@interface还有一些在其中定义的变量,这意味着什么?
Annotations(由@Interface定义)有点像bean.如果您使用注释,则此字段是可以/必须定义的属性.稍后可以通过反射API读取这些值.
例如@Controller
Spring中的Annotation:
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
String value() default "";
}
Run Code Online (Sandbox Code Playgroud)
带有名称value
的字段是可以在没有显式名称的情况下使用的字段:( @Controller("myUrl")
相同@Controller(value="myUrl")
)
您可以创建自己的元注释,收集其他几个Spring注释,以减少代码中的元样板:
@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public @interface ReadOnlyService {}
Run Code Online (Sandbox Code Playgroud)
然后你可以简单地写:
@ReadOnlyService
public class RoleService {
}
Run Code Online (Sandbox Code Playgroud)
Spring将找到@ReadOnlyService
并在语义上替换它:
@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public class RoleService {
}
Run Code Online (Sandbox Code Playgroud)
当然,当你有大量的服务使用相同的Spring注释注释时,自定义注释会付出代价,这些注释可以用一个名称很好的注释替换.
示例取自:避免Spring注释代码气味:使用Spring 3自定义注释
归档时间: |
|
查看次数: |
29454 次 |
最近记录: |