Annotation解释

(一)官方的定义:

An annotation is a form of metadata, that can be added to Java source code. Classes, methods, variables, parameters and packages may be annotated. Annotations have no direct effect on the operation of the code they annotate.

翻译一下大概就是:一种能够添加到 Java 源代码的语法元数据。类、方法、变量、参数、包都可以被注解,可用来将信息元数据与程序元素进行关联。Annotation 中文常译为“注解”。

(二)作用:

Annotations have a number of uses, among them:

Information for the compiler — Annotations can be used by the compiler to detect errors or suppress warnings.

Compile-time and deployment-time processing — Software tools can process annotation information to generate code, XML files, and so forth.

Runtime processing — Some annotations are available to be examined at runtime.

a. 标记,用于告诉编译器一些信息

b. 编译时动态处理,如动态生成代码

c. 运行时动态处理,如得到注解信息

Java注解可以用在构建期。当构建我们的工程时,构建进程会编译源码、生成xml文件,打包编译后的代码和文件到jar包。构建过程一般由构建工具自动完成,常用的构建工具有ant、maven。构建工具在构建时会自动扫描我们的代码,当遇到构建期注解时,会根据注解的内容生成源码或者其它文件。

(三)Annotation解析package javaeetutorial.hello1;


import javax.enterprise.context.RequestScoped;
import javax.inject.Named;

@Named
@RequestScoped
public class Hello {

    private String name;

    public Hello() {
    }

    public String getName() {
        return name;
    }

    public void setName(String user_name) {
        this.name = user_name;
    }
}

在上面的代码中,Hello类叫做管理bean类,它为facelets页面表达式所使用的name属性提供了getter和setter方法,默认该facelets页面表达式引用的是Hello类的名字,不过第一个字母是小写字母(例如:hello.name)。

        如果你使用的是默认的bean类的类名,你注解可以用@Model来替代@Named和@RequestScoped。@Model注释称为原型,是一个包含其他注释的注释的术语。

       在 Hello.java类中,注解javax.inject.Named和javax.enterprise.context.RequestScoped使用请求scope来标识Hello类为管理bean类。scope定义应用程序数据是如何保存和共享的。

      在JSF中最常用的scope如下:

                 Request(@RequestScoped):请求scope在Web应用程序中的单个HTTP请求期间仍然存在。像hello1应用,该应用由单个请求和响应组成,bean使用请求scope。

                 Session (@SessionScoped):会话scope持续存在于Web应用程序中的多个HTTP请求中。当应用程序包含需要维护数据的多个请求和响应时,bean使用会话scope。 

                 Application (@ApplicationScoped):应用程序scope在所有用户与Web应用程序的交互中持久存在。

原文地址:https://www.cnblogs.com/April315/p/10544501.html