从java注解 到spring注解的学习
1.java注解简单理解例子
注解类
package com.jhuc.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface Myanno { public String name() default "kk"; public String age(); }
package com.jhuc.annotation;
public class Source {
@Myanno(age = "1111")
public void sayhaha(){};
}
package com.jhuc.annotation; import java.lang.reflect.Method; public class Client{ public static void main(String[] args) throws SecurityException, NoSuchMethodException { Method method= Source.class.getDeclaredMethod("sayhaha"); if(method.isAnnotationPresent(Myanno.class)){ Myanno m=method.getAnnotation(Myanno.class); System.out.println(m.name()); System.out.println(m.age()); } } }
测试结果:
kk
1111
注解就是在一个类 或者方法 或者属性上标示下,然后这个类的反射Class中,会有这个注解的记录,可以获得这个注解,就可以做相应的动作
所以 注解可以用在哪个上面,方法 类 属性? 由@Target(ElementType.METHOD)决定
注解何时起作用,@Retention(RetentionPolicy.RUNTIME)决定
如果注解的属性不想必填,就可以写一个default值
Spring 注解
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd" > <bean id="helloWorld" class="com.jhuc.annotation.HelloWorld"> </bean> <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/> <bean id="bean1" class="com.jhuc.annotation.Bean1"> <property name="name" value="luce1"/> </bean> <bean id="bean2" class="com.jhuc.annotation.Bean2"> <property name="name" value="luce2"/> <property name="age" value="18"/> </bean> </beans>
package com.jhuc.annotation; import org.springframework.beans.factory.annotation.Autowired; public class HelloWorld { @Autowired private Bean1 bean1; @Autowired private Bean2 bean2; public String toString() { return "bean1:" + bean1.getName() +"\n" + "bean2:" + bean2.getAge()+bean2.getName(); } }
在一个个创建bean时,AbstractAutowireCapableBeanFactory中的populateBean方法中
在解析属性时,回去load出该类class所拥有的方法和属性注解到一个集合里面
如果集合不为空,则进行注解属性赋值