Bạn có thể thực hiện việc này với AspectJ.
Tạo chú thích @Configurable:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Configurable {
}
Tạo một AspectJ @Aspect tương tự như sau:
@Aspect
public class ConfigurableInjectionAspect {
private Logger log = Logger.getLogger(getClass().getName());
@Pointcut("@within(Configurable) && execution(*.new(..)) && target(instantiated)")
public void classToBeInjectedOnInstantiation(Object instantiated) {}
@After(value = "classToBeInjectedOnInstantiation(instantiated)",
argNames = "instantiated")
public void onInstantiation(Object instantiated) {
Injector injector = InjectorHolder.getInjector();
if (injector == null) {
log.log(Level.WARNING, "Injector not available at this time");
} else {
injector.injectMembers(instantiated);
}
}
}
Tạo (và sử dụng) một lớp giữ cho vòi phun của bạn:
public final class InjectorHolder {
private static Injector injector;
static void setInjector(Injector injector) {
InjectorHolder.injector = injector;
}
public static Injector getInjector() {
return injector;
}
}
Định cấu hình META-INF/aop.xml:
<aspectj>
<weaver options="-verbose">
<include within="baz.domain..*"/>
<include within="foo.bar.*"/>
</weaver>
<aspects>
<aspect name="foo.bar.ConfigurableInjectionAspect"/>
</aspects>
</aspectj>
Bắt đầu VM của bạn với aspectjweaver:
-javaagent:lib/aspectjweaver.jar
Chú thích các lớp miền của bạn:
@Entity
@Table(name = "Users")
@Configurable
public class User {
private String username;
private String nickname;
private String emailAddress;
@Inject
private transient UserRepository userRepository
public User() {}
}
Nguồn
2010-07-28 12:33:57
Cảm ơn, một giải pháp codeweaving như Salve thực sự có thể làm các trick. Tôi đã thử Salve, nhưng nó có tài liệu giới hạn và tôi không thể làm cho nó làm bất cứ điều gì (thậm chí không phải là một thông báo lỗi). Chỉ cần hy vọng cho một số mã mẫu đơn giản, ví dụ với AspectJ hoặc AOP tốt hơn. – Kdeveloper
@Kdeveloper: Tôi không có kinh nghiệm với Salve nên tôi không thể giới thiệu nó nhưng nó có thể cung cấp cho bạn một số ý tưởng để thực hiện một cái gì đó tương tự đó là lý do tại sao tôi đề cập đến nó –