spring @Value注解原理梳理及自定义实现@MyValue注解
目录
- @Value注解如何使用?
- 探索@Value注解的实现过程
- 自定义实现@MyValue注解
1. @Value注解如何使用?
- 在项目中我们经常需要用到使用读取配置文件,进行属性值的注入很方便;
- 很多时候我们不想手动的去初始化配置,在spring就提供了很强大的属性依赖配置注解@Value来实现,在实现bean创建后,自动实现属性的注入功能. 接下来我们将先 从一个简单的例子来描述,如何使用@Value注解,能达到什么效果,到最后我们自己动手实现自己的属性注解.
1.1 准备
创建maven项目,导入spring相关的包的此处省略…
- 配置一个注解类,能让spring 管理, AppConfig
package com.mp.aop.annotation.day02.config;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.stereotype.Component;
@ComponentScan("com.mp.aop.annotation.day02.service")
public class MyConfig {
}
-
此处配置@ComponentScan 注解扫描指定的package及其子包;将其所有实现了@bean @Component 等注解的类统一交由sping IOC来管理
-
准备程序入口,访问整体的spring bean
package com.mp.aop.annotation.day02;
import com.mp.aop.annotation.day02.config.MyConfig;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import java.util.stream.Stream;
public class MainManager {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
// 已经完成了整个spring容器的初始化;这里先简单的获取下,我们容器负责管理的所有bean
Stream.of(context.getBeanDefinitionNames()).forEach(s -> System.out.println(s));
}
}
- 执行主入口程序,可以获取整个spring管理系统,自定义获取bean及其操作。
org.springframework.context.annotation.internalConfigurationAnnotationProcessor
org.springframework.context.annotation.internalAutowiredAnnotationProcessor
org.springframework.context.annotation.internalCommonAnnotationProcessor
org.springframework.context.event.internalEventListenerProcessor
org.springframework.context.event.internalEventListenerFactory
myConfig
可以看到,刚开始程序会创建6个bean,其中5个为spring容器需要初始化(后面会详细介绍分析);另外一个为我们添加的配置类.
- 添加一个带@Value注解的类 Person
package com.mp.aop.annotation.day02.service;
import com.mp.aop.annotation.MyAnnotation;
import lombok.Data;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
im