一文讲懂@Inherited

93 阅读1分钟

点击@Inherited进去可以看到它的作用目标限定为注解,只能作用在注解上,是元注解。被它修饰的注解运用在父类中时可以被子类继承

image.png

下面我们以一个实际案例来展示它的作用效果

首先我们创建两个注解,一个注解有@Inherited修饰,命名为@HasInherited

image.png

一个注解没有@Inherited修饰,命名为@NoInherited

image.png

再创建一个父类,和一个子类继承它

image.png image.png

再创建一个测试类

image.png

我们可以看到当父类被@NoInherited修饰时,子类不能继承父类的注解

image.png

而把父类改为被@HasInherited修饰时

image.png

子类就可以继承父类的注解

image.png

同理我们可以再以@SpringBootApplication注解为例

image.png

我们可以看到@SpringBootApplication注解有@Inherited修饰,即代表当我们的RunApplication作为父类时,子类继承它是可以继承他的@SpringBootApplication注解的,下面我们来验证一下

image.png

我们创建一个RunSubApplication类来继承RunApplication

image.png

我们在子类中启动程序可以看到程序被SpringBoot启动了,即代表子类继承了@SpringBootApplication注解

image.png