【Java EE 学习 49 下】【Spring学习第一天】【MVC】【注解回顾】

一、MVC

  1.使用Spring有一个非常大的好处,那就是能够实现完全面向接口编程,传统的使用Dao、Service并不能实现完全的面向接口编程。

  2.示例:https://github.com/kdyzm/day45_spring_mvc

二、注解示例

  1.定义注解方法示例:

package com.kdyzm.spring.annotation;

import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE,ElementType.METHOD,ElementType.FIELD})
public @interface MyAnnotation {
    String value() default "默认值";
}

  2.使用注解方法示例

package com.kdyzm.spring.annotation;

@MyAnnotation
public class Person {
    @MyAnnotation("name属性")
    public String name;

    @Override
    @MyAnnotation("toString方法!!!")
    public String toString() {
        return "Person [name=" + name + "]";
    }

    public String getName() {
        return name;
    }

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

  3.解析注解方法示例

package com.kdyzm.spring.annotation;

import java.lang.reflect.Field;
import java.lang.reflect.Method;



public class Test {
    public static void main(String[] args) {
        Class<Person> clazz=Person.class;
        if(clazz.isAnnotationPresent(MyAnnotation.class)){
            MyAnnotation annotation=(MyAnnotation) clazz.getAnnotation(MyAnnotation.class);
            System.out.println(annotation.value());
        }
        Field [] fields=clazz.getFields();
        for(Field field:fields){
            System.out.println(field.getName());
            if(field.isAnnotationPresent(MyAnnotation.class)){
                MyAnnotation annotation=field.getAnnotation(MyAnnotation.class);
                System.out.println(annotation.value());
            }
        }
        
        Method[]methods=clazz.getMethods();
        for(Method method:methods){
            System.out.println(method.getName());
            if(method.isAnnotationPresent(MyAnnotation.class)){
                MyAnnotation annotation = method.getAnnotation(MyAnnotation.class);
                System.out.println(annotation.value());
            }
        }
    }
}

  4.解析结果:

默认值
name
name属性
toString
toString方法!!!
getName
setName
wait
wait
wait
equals
hashCode
getClass
notify
notifyAll

 

posted @ 2015-09-28 14:48  狂盗一枝梅  阅读(227)  评论(0编辑  收藏  举报