欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 健康 > 养生 > Spring学习笔记_25——@DeclareParents

Spring学习笔记_25——@DeclareParents

2025/2/10 21:53:26 来源:https://blog.csdn.net/LuckyLay/article/details/143504707  浏览:    关键词:Spring学习笔记_25——@DeclareParents

@DeclareParents

1. 介绍

@DeclareParents 注解是 Spring AOP(面向切面编程)中的一个特性,用于实现引入增强(Introduction Advice)。引入增强允许我们向现有的类添加新的接口或方法。这意味着通过使用 @DeclareParents,你可以让一个类“看起来”像是实现了某个接口,或者拥有某些它原本没有的方法。

基本概念:

  • 引入增强:是一种特殊类型的增强,它可以给目标对象动态地添加一些业务方法或接口。
  • 目标对象:是指将要应用增强逻辑的对象。
  • 接口或方法:通过引入增强可以为这些对象添加的接口实现或方法。

2. 场景

当你需要在多个类中添加相同的行为或功能,而不希望修改这些类的源代码时,可以考虑使用 @DeclareParents。例如,你可能想要为系统中所有的DAO层组件添加缓存支持,而不需要去修改每个DAO类的代码。

3. 源码

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.FIELD)
public @interface DeclareParents {// 指定目标类型的表达式,如果在全类名的后面添加 + ,则表示的是当前类及其子类。String value();// 指定方法或者字段的默认实现类Class defaultImpl() default DeclareParents.class;
}

4. Demo

定义一个Person

package com.example.service;public class Person {private String name;public Person(String name) {this.name = name;}public String getName() {return name;}public void setName(String name) {this.name = name;}
}

定义接口

package com.example.aspect;public interface Greeting {String sayHello();
}

定义实现

package com.example.aspect;public class GreetingImpl implements Greeting {@Overridepublic String sayHello() {return "Hello!";}
}

配置AOP使用@DeclareParents

package com.example.app;import com.example.aspect.Greeting;
import com.example.aspect.GreetingImpl;
import com.example.service.Person;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.EnableAspectJAutoProxy;@Configuration
@EnableAspectJAutoProxy
public class AppConfig {@Beanpublic Person person() {return new Person("John Doe");}@Bean@DeclareParents(value = "com.example.service.Person", defaultImpl = GreetingImpl.class)public Greeting greeting() {return null; // 返回 null,因为实际的实现是由 AOP 框架提供的}
}

测试

package com.example.app;import com.example.service.Person;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;public class Main {public static void main(String[] args) {ApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class);Person person = context.getBean(Person.class);// 由于 Person 类通过 AOP 动态实现了 Greeting 接口,所以这里可以强转Greeting greeting = (Greeting) person;System.out.println(greeting.sayHello());}
}

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com