spring中自定义注解

发布于 2024-12-11 04:20:24 字数 396 浏览 0 评论 0原文

我见过一些使用自定义注释的例子。任何

@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 {
}

人都可以告诉我们为什么使用这个吗?

I have seen few examples where customized annotations were used. example

@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 {
}

Can anyone tell why we use this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

2024-12-18 04:20:24

Spring支持许多Annotation“元注释”的概念。 (我不确定它是否适合所有人。)

这意味着您可以构建自己的注释并使用 springs“核心”注释之一对该注释进行注释。

例如:

@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Service
public @interface MyService {

}

那么你可以使用这个注解来代替@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 自定义注释

如果您想了解此技术的强大功能,可以查看上下文和依赖注入框架。


评论中的问题:

@interface内部也定义了一些变量,这意味着什么?

注释(由 @Interface 定义)的工作方式有点像 bean。如果您使用注释,此字段是可以/必须定义的属性。稍后可以通过反射 API 读取这些值。

例如 Spring 中的 @Controller 注解:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
   String value() default "";
}

名称为 value 的字段是无需显式命名即可使用的字段: (@Controller("myUrl" ) 是相同的 @Controller(value="myUrl"))

Spring supports for many Annotation the concept of "meta-annotation". (I am not sure if it is for all.)

This mean that you can build your own annotation and annotate the annotation with one of springs "core" annotations.

For example:

@Target({ ElementType.FIELD, ElementType.PARAMETER, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Service
public @interface MyService {

}

Then you can use this annotation instead of @Service. (Btw: @Service, @Repository, @Controller use the same technique to "inherit" from @Component)


One example that make heavy use of this is "inherit" from @Qualifier.
For an example and some explanation have a look at Spring Reference Chapter: 3.9.3 Fine-tuning annotation-based autowiring with qualifiers (The Example with @Genre is at the end of the chapter.)

One very usefull construct that can be done with that technique is, that it enables you to combine several Annotations to a (in your use case) more meaning full. So instead of writing at every class of some type allways the same two annotations, for example: @Service and @Qualifiyer("someting") (the org.springframework.beans.factory.annotation.Qualifier). You can create your custom annotation that is annotated with this two annotations, and then use in your beans only this one custom annotation. (@See Avoid Spring Annotation Code Smell Use Spring 3 Custom Annotations)

If you want to see how powerfull this technique can be use, you can have a look at Context and Dependency Injection Framework.


Question from the comment:

The @interface also has some variables defined inside it, what does that signify?

The Annotations (defined by @Interface) work a bit like beans. This Fields are the properties that can/must be define if you use the annotations. The values can be later on be read via reflection API.

For example the @Controller Annotation in Spring:

@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
@Component
public @interface Controller {
   String value() default "";
}

The field with name value is that field that can be used without explicit name it: (@Controller("myUrl") is the same @Controller(value="myUrl"))

幽梦紫曦~ 2024-12-18 04:20:24

您可以创建自己的元注释来收集其他几个 Spring 注释,以减少代码中的元样板:

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public @interface ReadOnlyService {}

然后您可以简单地编写:

@ReadOnlyService
public class RoleService {

}

将找到 @ReadOnlyService 并在语义上将其替换为:

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public class RoleService {

}

Spring 当您有大量使用同一组 Spring 注释进行注释的服务(可以用一个命名良好的注释替换)时,使用自定义注释当然是值得的。

示例取自: 避免 Spring 注解代码异味:使用Spring 3自定义注解

You can create your own meta-annotations that collect several other Spring annotations to reduce meta-boilerplate in your code:

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public @interface ReadOnlyService {}

And then you can simply write:

@ReadOnlyService
public class RoleService {

}

Spring will find the @ReadOnlyService and semantically replace it with:

@Service
@Scope(value = "prototype")
@Transactional(readOnly = true, rollbackFor = RuntimeException.class)
public class RoleService {

}

Of course having custom annotations pays of when you have tons of services annotated with the same set of Spring annotations that can be replaced with one, well named annotation.

Examples taken from: Avoid Spring Annotation Code Smell: Use Spring 3 Custom Annotations

北斗星光 2024-12-18 04:20:24

自定义注释本身不会执行任何操作。它们是代码中的简单标记。它们的真正力量来自于寻找特定注释的工具。就像其他一些答案提到的那样,Spring 有多种注释用途,现在还有用于定义您自己的组件类型的机制。相当整洁。另一个例子,几周前我使用 AOP 和一些自定义注释来提供简单的方法级结果缓存。现在我已经有了缓存引擎,并定义了适当的 AOP 挂钩,如果我想缓存一个方法,我只需添加该注释即可。有些人只是将注释用作花哨的元数据以提高可读性。

归根结底,它们是一个相当简单的工具,可以用于很多事情。

Custom annotations do not do anything on their own. They are simple markers in code. Their real power comes from tools that look for specific annotations. Like some of the other answers mention, Spring has several uses for annotations and now mechanisms for defining your own component types. Pretty neat. Another example, a few weeks ago I used AOP and a few custom annotations to provide simple method level result caching. Now that I have the caching engine in place, and the appropriate AOP hooks defined, if I want to cache a method, I simply add that annotation. Some people simply use the annotations as fancy metadata to improve readability.

At the end of the day, they are a fairly simple tool that you can use for a great number of things.

救星 2024-12-18 04:20:24

使用自定义注释的最好的部分是您不必进行任何配置,Spring 将自动检测这些 bean 是服务组件,并且一切都会正常工作。自定义注释是 Spring 中添加的一个非常小的功能,但非常有用。有关详细信息,请查看此

http://java.dzone.com/articles/avoid-spring-annotation-code-smell-use-spring3-custom-annotations

The best part of using custom annotations is that you don't have to make any configuration, Spring will auto detect that these beans are service components and everything will work fine. Custom Annotations are a very small feature added in Spring but are very useful.For details take a look at this

http://java.dzone.com/articles/avoid-spring-annotation-code-smell-use-spring3-custom-annotations

满天都是小星星 2024-12-18 04:20:24

两个选项:

  • 您需要在自定义注释上使用@Component注释。这样您就可以使用自定义注释将类标记为 bean。此外,您还可以

  • 限定符 - 您可以使用限定符注释(使用@Qualifier元注释进行注释)来区分同一接口的实现。

Two options:

  • you need the @Component annotation on your custom annotation. That way you can use your custom annotation to mark classes as beans. In addition, you can add a default scope and other meta-information

  • qualifiers - you can use qualifier annotations (annotated with the @Qualifier meta-annotation) to distinguish between implementations of the same interface.

暮年 2024-12-18 04:20:24

一种常见的模式也是在 AOP 切入点中使用注释。不是专门针对 Spring,但在使用 Spring AOP 时经常使用。

A common pattern is also to use annotations in AOP pointcuts. Not specifically Spring, but often employed when making use of Spring AOP.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文