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的相關知識。