前言:
注解@Annotion是Java非常重要的一部分,
自从1.5版本推出以来就被非常广泛的运用到各种框架和应用,
已经成为了Java一块重要的拼图了.
而C#的Attribute和@Annoation的功能相近,
同样也是配合二者反射的使用给类/接口/…添加动态的运行时的信息
这里先以Java使用Annoation为例,
Java使用Annoation:山寨一个@Bean
@Bean是spring的一个最基础的注解,
只要添加后就可会为类和方法在容器中创建一个实例
这个功能并不难,在不限制生命周期的情况下,现在我们可以自己实现一下
1.定义一个容器(其实就是一个Map)
public class MySpringContainer {
public static HashMap<String,Object> theContainer = new HashMap<String, Object>();
public static HashMap<String, Object> getContainer(){
return theContainer;
}
}
2.定义注解@Bean
注解的定义只需要记住4个元注解即可
- @Target({ElementType枚举类,用于规定注解的使用范围})
- @Retention(RetentionPolicy枚举类型,用于指定注解信息的保留,有Souce只保留在编译时,Class保存在编译后的类文件,RUNTIME在(VM)程序运行时也保留)
- @Documented
- @Inherited //是否可以被继承,这点很常见,在spring中,@Component继承了@Bean,@Servce,@Controller,@Repository…则继承了@Component
@Target({
ElementType.TYPE}) //可以设置在类上
@Retention(RetentionPolicy.RUNTIME) //保留策略
@Inherited
@Documented
public @interface Bean {
//注解的定义和接口很像,同样也只能在其中声明方法(但其方法本质是一种属性,不需要实现,这是和接口不一样的)
String O_id();
}
3.随便定义一个pojo类,应用注解
@Bean(O_id = "theOne") //tip:如果方法名为value则可以不用写O_id
public class Pet {
private String id;
private String name;
private String Owner;
public String getId() {
return id;
}
public Pet() {
System.out.println("使用了無參的構造方法");
id = "deffault";
name = "deffault";
Owner = "deffault";
}
public void setId(String id) {
this.id = id;
}
public String getName(