博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
创建spring自定义注解进行自动装配
阅读量:7051 次
发布时间:2019-06-28

本文共 2061 字,大约阅读时间需要 6 分钟。

1、创建自定义注解

1 import org.springframework.beans.factory.annotation.Qualifier; 2 import java.lang.annotation.ElementType; 3 import java.lang.annotation.Retention; 4 import java.lang.annotation.RetentionPolicy; 5 import java.lang.annotation.Target; 6  7  8 @Target({ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE}) 9 @Retention(RetentionPolicy.RUNTIME)10 @Qualifier11 public @interface StringedInstrument {12 13 }
View Code

Retention注解有一个属性value,是RetentionPolicy类型的,Enum RetentionPolicy是一个枚举类型,

用@Retention(RetentionPolicy.CLASS)修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,但不会被虚拟机读取在运行的时候;

用@Retention(RetentionPolicy.SOURCE )修饰的注解,表示注解的信息会被编译器抛弃,不会留在class文件中,注解的信息只会留在源文件中;
用@Retention(RetentionPolicy.RUNTIME )修饰的注解,表示注解的信息被保留在class文件(字节码文件)中当程序编译时,会被虚拟机保留在运行时,

2、创建instrument ,并使用注解

 

1 @StringedInstrument2 public class Instrument {3 4     public void play() {5         System.out.println("playing...");6     }7 }

 

3、创建表演者kenny,进行自动装配

1 import org.springframework.beans.factory.annotation.Autowired; 2  3 public class Kenny { 4  5     @Autowired 6     @StringedInstrument 7     private Instrument instrument; 8  9     public Instrument getInstrument() {10         return instrument;11     }12 13     public void setInstrument(Instrument instrument) {14         this.instrument = instrument;15     }16 17 18     public Kenny(Instrument instrument) {19         this.instrument = instrument;20     }21 22     public void  perform(){23         instrument.play();24     }25 }

4、配置spring

1 
2
6 7
8 9
10
11 12
13 14
15 16

5、测试

1 import org.springframework.context.ApplicationContext; 2 import org.springframework.context.support.ClassPathXmlApplicationContext; 3  4  5 public class Test { 6     public static void main(String[] args) { 7  8         ApplicationContext context = new ClassPathXmlApplicationContext("context.xml"); 9         Kenny kenny = (Kenny) context.getBean("kenny");10         kenny.perform();11     }12 }

 

转载于:https://www.cnblogs.com/ethereal/p/6013589.html

你可能感兴趣的文章
爱奇艺体育获5亿元战略融资 ,IDG资本、汇盈博润领投
查看>>
三目运算-高级嵌套用法思路教程
查看>>
从编程小白到全栈开发:寻找代码中的问题
查看>>
如何处理地图投影转换
查看>>
区块链技术公司 看区块链数据如何实现安全共享
查看>>
HttpClient-4.5总结(1)
查看>>
Linux_异常_03_Failed to restart iptables.service: Unit not found.
查看>>
LeetCode 169 Majority Element(主要元素)(vector、map)
查看>>
mysql中的几个常用的方法
查看>>
Google 的Android Splash
查看>>
2- 快速上手Linux玩转典型应用- 搭建Linux环境
查看>>
树莓派 之 微信聊天机器人(ItChat)
查看>>
如何学习一门编程语言
查看>>
Java__线程---基础知识全面实战---坦克大战系列为例
查看>>
js时间戳转换日期格式和日期计算
查看>>
真的,移动端尺寸自适应与dpr无关
查看>>
Odoo自定义报表 - 浅析
查看>>
Boss直聘邮件通知小脚本
查看>>
初探XRebel
查看>>
面对自动驾驶的道德迷宫,奔驰选择弃路人救乘客
查看>>