gpt4 book ai didi

hibernate - 实体bean的Guice依赖注入(inject)?

转载 作者:行者123 更新时间:2023-12-04 11:31:15 25 4
gpt4 key购买 nike

对于富域驱动设计,我想使用 JPA/Hibernate 实体 bean 上的 Guice 依赖注入(inject) .我正在寻找与非 Spring bean 的 Spring @configurable 注释类似的解决方案。

有人知道图书馆吗?任何代码示例?

最佳答案

您可以使用 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);
}
}
}

为您的注入(inject)器创建(并使用)一个持有类:
public final class InjectorHolder {

private static Injector injector;

static void setInjector(Injector injector) {
InjectorHolder.injector = injector;
}

public static Injector getInjector() {
return injector;
}
}

配置 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>

使用 aspectjweaver 启动 VM:
-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() {}
}

关于hibernate - 实体bean的Guice依赖注入(inject)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3273601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com