आप इसे AspectJ के साथ कर सकते हैं।
@Configurable टिप्पणी बनाएं:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.TYPE})
public @interface Configurable {
}
एक AspectJ @Aspect इस के समान बनाएं: (और उपयोग) अपने इंजेक्टर के लिए
@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);
}
}
}
बनाएँ होल्डिंग वर्ग:
public final class InjectorHolder {
private static Injector injector;
static void setInjector(Injector injector) {
InjectorHolder.injector = injector;
}
public static Injector getInjector() {
return injector;
}
}
मेटा-आईएनएफ/एओपी.एक्सएमएल कॉन्फ़िगर करें:
<aspectj>
<weaver options="-verbose">
<include within="baz.domain..*"/>
<include within="foo.bar.*"/>
</weaver>
<aspects>
<aspect name="foo.bar.ConfigurableInjectionAspect"/>
</aspects>
</aspectj>
aspectjweaver के साथ अपने वीएम शुरू
:
-javaagent:lib/aspectjweaver.jar
एन्नोटेट आपके डोमेन कक्षाएं:
@Entity
@Table(name = "Users")
@Configurable
public class User {
private String username;
private String nickname;
private String emailAddress;
@Inject
private transient UserRepository userRepository
public User() {}
}
स्रोत
2010-07-28 12:33:57
धन्यवाद, साल्वे की तरह एक codeweaving समाधान वास्तव में चाल कर सकता है। मैंने साल्व की कोशिश की, लेकिन इसमें सीमित दस्तावेज है और मैं इसे कुछ भी नहीं कर सकता (यहां तक कि एक त्रुटि संदेश भी नहीं)। बस कुछ सरल नमूना कोड की उम्मीद है, उदाहरण के लिए AspectJ या इससे भी बेहतर एओपी। – Kdeveloper
@Kdeveloper: मुझे साल्व के साथ कोई अनुभव नहीं है, इसलिए मैं इसकी अनुशंसा नहीं कर सकता लेकिन यह आपको कुछ ऐसा लागू करने के लिए कुछ विचार दे सकता है, इसलिए मैंने इसका उल्लेख किया है –