Spring注解开发之HelloWorld

注解

注解

Spring中的注解是通过Java的元注解进行实现的,所以本文首先对Java注解进行简单的介绍。Java 注解(Annotation)又称 Java 标注,是 JDK5.0 引入的一种注释机制。本质是对类、字段以及方法等进行一种解释和说明。Java中注解分为元注解和非元注解,元注解是用来定义注解的一种特殊注解。接下来对元注解进行简单的介绍

元注解

@Retention - 标识这个注解保存在代码中,还是编入class文件中,或者是在运行时。
@Documented - 标记这些注解是否包含在用户文档中。
@Target - 标记这个注解应该是哪种 Java 成员:类、方法、构造器,属性等。
@Inherited - 标记这个注解是否可以被当前类的子类进行继承(默认 注解并没有继承于任何子类)

注解定义好之后,接下来看注解使用的实例:模拟Spring中注解的实现。

注解使用实例

流程图

注解的使用流程

代码

定义注解

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
 
@Target(value = {ElementType.CONSTRUCTOR,ElementType.FIELD,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyAnnoation {
    String value();
}

在java代码中使用注解

(1)定义一个Person类,利用定义好的注解给Person类中的属性赋值
public class Person {

public String getName() {
    return name;
}

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

@MyAnnoation("smart")
private String name;

public Integer getAge() {
    return age;
}

public void setAge(Integer age) {
    this.age = age;
}

@Override
public String toString() {
    return "Person{" +
            "name='" + name + '\'' +
            ", age=" + age +
            '}';
}

@MyAnnoation("12")
private Integer age;

}

获取、解析注解

import java.lang.annotation.Annotation;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Scanner;
 
public class MySpring {
    public Object getBean(String packagePath){
        Object result = null;
        Scanner scanner = new Scanner(System.in);
        try{
            //创建类
           Class<?> classObject = Class.forName(packagePath);
           result = classObject.newInstance();
           //获取类的属性
            Field[] fields = classObject.getDeclaredFields();
            for (Field field: fields) {
                //获取属性名
                String name = field.getName();
                String firstLetter = name.substring(0,1).toUpperCase();
                String otherLetter = name.substring(1);
                StringBuilder propertiesMethod = new StringBuilder("set");
                propertiesMethod.append(firstLetter).append(otherLetter);
                Class fieldClass = field.getType();
                Method method = classObject.getMethod(propertiesMethod.toString(),fieldClass);
                //参数可以从文件中读取或者从注解中读取
                Annotation annotation = field.getAnnotation(MyAnnoation.class);
                Constructor con = fieldClass.getConstructor(String.class);
                method.invoke(result,con.newInstance(((MyAnnoation) annotation).value()));
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return result ;
    }
}

Spring注解开发之Helloworld

导入依赖项

<dependencies>
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.4</version>
            <scope>provided</scope>
        </dependency>


        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>4.3.5.RELEASE</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.13</version>
            <scope>test</scope>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.2.4.RELEASE</version>
        </dependency>

    </dependencies>

定义Bean

package spring.annotation.day1.ioc.bean;

import lombok.*;

import java.util.*;

@Getter
@Setter
@ToString
@AllArgsConstructor
@NoArgsConstructor
public class Person {

/**
 * 姓名
 */
private String name;

/**
 * 年龄
 */
private Integer age;

/**
 * 字符串列表
 */
List<String> stringList;


/**
 * set集合
 */
Set<String> stringSet;


/**
 * map对象
 */
Map<String ,String> stringMap;


/**
 * 属性对象
 */
Properties properties;

}

定义配置类

package spring.annotation.day1.ioc.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import spring.annotation.day1.ioc.bean.Person;

@Configuration
public class SpringConfig {

    /**
     * 容器中注入bean,默认使用方法名作为id,以在Bean注解中指定Id
     * @return
     */
    @Bean
    public Person person(){
        return new Person();
    }
}

通过观看代码发现 @Bean注解和@Configure注解均是通过元注解定义实现的,也验证了上文的观点。
在这里插入图片描述
在这里插入图片描述

测试用例

package spring.annotation.day1.test.ioc;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import spring.annotation.day1.ioc.config.SpringConfig;
import spring.annotation.day1.ioc.bean.Person;

import java.util.Arrays;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = SpringConfig.class)
public class SpringAnnotationTest {

    @Test
    public void annotationTest(){
       //获取Spring上下文环境
        ApplicationContext applicationContext = new AnnotationConfigApplicationContext(SpringConfig.class);
        //使用上下文环境获取Bean
        Person person = (Person)applicationContext.getBean("person");
        System.out.println(person);
        //获取Spring中已经定义好的Bean名称
        String[] beanNames = applicationContext.getBeanDefinitionNames();
        Arrays.asList(beanNames).forEach(System.out::println);
    }
}

测试结果

在这里插入图片描述

总结

通过本文可以对Java中注解概念和应用有个初步的了解,对Spring中的注解使用有个初步的掌握,接下会有文章继续讲解Spring的相关知识。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值