@Target({ java.lang.annotation.ElementType.FIELD,
java.lang.annotation.ElementType.METHOD,
java.lang.annotation.ElementType.PARAMETER,
java.lang.annotation.ElementType.ANNOTATION_TYPE })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Value {
public abstract String value();
}
注解定义上的注解 @Target:
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Target {
ElementType[] value();
}
其中ElementType的定义为:
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE
}
这里表示了一个注解修饰的对象:
1. Type 类型
2. Field 成员
3. Method 方法
4. Parameter 参数
5. Constructor 构造函数
6. Local-Variable 局部变量
7. Annotation-Type 注解
8. Package 包
那么在不指定Target的情况下,默认是?
尝试了下,创建一个注解,不指定Target,在方法、成员变量上使用都没有问题。那接下来的问题,使用注解可以达到说明目的?也就是为什么要引入注解这样的概念?
从最初JSE5引入注解,为了减少代码的编写量?弥补代码不能表达的一些功能?
譬如在本文开始处,@Value 可以用来做什么?首先,来看应用在Field上面的例子:
package test;
import org.springframework.beans.factory.annotation.Value;
public class NatTest {
@Value("1")
int age;
@Value("lizh")
String name;
@Override
public String toString() {
return "NatTest [age=" + age + ", name=" + name + "]";
}
public static void main(String[] args) {
NatTest nat = new NatTest();
System.out.println(nat);
}
}
直觉@Value就像初始化一样使用,但其参数只能接受String类型,那么整形数字如何实现初始化呢?在不考虑整形的情况下,那字符串类型的变量是否能直接通过@Value初始化呢?参见代码中成员变量name。
以上代码运行的结果:
NatTest [age=0, name=null]
可见,@Value并不是直接使用值去初始化成员变量。那它又是如何使用的?
程序需要使用配置,很多配置程序只要读取一次,期间不允许变化(不需要后续动态加载),譬如数据库连接配置。那么,很正常的想法,配置按一定的格式存在一个配置文件中,程序启动的时,读取配置文件,根据格式读取到对应的值。这里涉及到文件的读取,配置文件的格式等问题。而且这个操作,在类似场景的代码基本差不多。@Value就是为了解决这个问题。
每一点小的改进都是值得推荐的
于是,增加配置文件: test.properties
nat.age=30
nat.name="lizh"
如何读取配置文件?
以上例子尝试无果。问题:@Value里的值什么会赋给变量?
带着问题,看看 ImportNew 是如何分析的。
http://www.importnew.com/10294.html