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

本文深入探讨了MVC架构模式及其在Spring框架中的应用,通过具体示例讲解了如何利用Spring实现面向接口编程,同时提供了注解定义、使用及解析的详细代码示例。

一、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

 

转载于:https://www.cnblogs.com/kuangdaoyizhimei/p/4843978.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值