@Target
- 描述注解的作用范围
ElementType.ANNOTATION_TYPE 只可以标记注解类型
ElementType.CONSTRUCTOR 标记构造函数
ElementType.FIELD 标记字段或属性
ElementType.LOCAL_VARIABLE 标记本地变量
ElementType.METHOD 标注方法
ElementType.PACKAGE 标注包
ElementType.PARAMETER 标记方法的变量
ElementType.TYPE 标记类中的任何元素
public enum ElementType {
/** Class, interface (including annotation type), or enum declaration */
TYPE,
/** Field declaration (includes enum constants) */
FIELD,
/** Method declaration */
METHOD,
/** Formal parameter declaration */
PARAMETER,
/** Constructor declaration */
CONSTRUCTOR,
/** Local variable declaration */
LOCAL_VARIABLE,
/** Annotation type declaration */
ANNOTATION_TYPE,
/** Package declaration */
PACKAGE,
/**
* Type parameter declaration
*
* @since 1.8
*/
TYPE_PARAMETER,
/**
* Use of a type
*
* @since 1.8
*/
TYPE_USE
}
@Retention
- RetentionPolicy.SOURCE:注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
- RetentionPolicy.CLASS:注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
- RetentionPolicy.RUNTIME:注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;
@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.ANNOTATION_TYPE)
public @interface Retention {
/**
* Returns the retention policy.
* @return the retention policy
*/
RetentionPolicy value();
}
public enum RetentionPolicy {
/**
* 注解只保留在源文件,当Java文件编译成class文件的时候,注解被遗弃;
*/
SOURCE,
/**
* 注解被保留到class文件,但jvm加载class文件时候被遗弃,这是默认的生命周期;
*/
CLASS,
/**
* 注解不仅被保存到class文件中,jvm加载class文件之后,仍然存在;
*/
RUNTIME
}
@Inherited(转载)
指示批注类型是自动继承的。如果在注释类型声明中存在继承的元注释,并且用户在类声明上查询注释类型,并且类声明对该类没有注释,那么该类的超类将自动被查询到注释类型。这个过程将被重复,直到找到这个类型的注释,或者到达类层次结构(对象)的顶端。如果没有超类具有此类的注释,那么查询将表明该类没有此类注释
类继承关系中@Inherited的作用
类继承关系中,子类会继承父类使用的注解中被@Inherited修饰的注解
接口继承关系中@Inherited的作用
接口继承关系中,子接口不会继承父接口中的任何注解,不管父接口中使用的注解有没有被@Inherited修饰
类实现接口关系中@Inherited的作用
类实现接口时不会继承任何接口中定义的注解
作者:氨基钠
链接:https://www.jianshu.com/p/7f54e7250be3
@Bean--Spring注解
- @Bean是一个方法级别上的注解,主要用在@Configuration注解的类里,也可以用在@Component注解的类里。
//改注解可以作用在方法和注解上
@Target({ElementType.METHOD, ElementType.ANNOTATION_TYPE})
//运行时仍会保存到内存中
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Bean {
/**
* bean的名字(多例可以指定多个名称),如不指定默认使用方法名,
*/
String[] name() default {};
/**
* 默认--表示不通过自动装配。
* NO(AutowireCapableBeanFactory.AUTOWIRE_NO),
* 通过名称进行自动装配
* BY_NAME(AutowireCapableBeanFactory.AUTOWIRE_BY_NAME),
* 常量,通过类型进行自动装配
* BY_TYPE(AutowireCapableBeanFactory.AUTOWIRE_BY_TYPE);
*/
Autowire autowire() default Autowire.NO;
/**
* bean初始化调用的方法名
*/
String initMethod() default "";
/**
* 实例销毁的时候调用的方法名
*/
String destroyMethod() default AbstractBeanDefinition.INFER_METHOD;
}
示例代码如下:向spring容器里注入一个名字为方法名(如果指定name则为指定的名称)的实例,初始化时调用init方法,销毁时调用destroy方法。
public class MyBean {
public MyBean(){
System.out.println("MyBean Initializing");
}
public void init(){
System.out.println("Bean 初始化方法被调用");
}
public void destroy(){
System.out.println("Bean 销毁方法被调用");
}
}
@Configuration
public class AppConfig {
@Bean(initMethod = "init", destroyMethod = "destroy")
public MyBean myBean(){
return new MyBean();
}
}