简体   繁体   English

Spring Prototype bean具有不同的参数

[英]Spring Prototype bean with different parameters

I want to inject a prototype scoped bean into a singleton. 我想将一个原型scoped bean注入一个单例。 This prototype bean should only be created once for each Singleton it is injected in (which is the case by default as far as I understand). 这个原型bean只应为它注入的每个Singleton创建一次(据我所知,默认情况下是这种情况)。 However, I do want a slightly different bean each time, so I want to be able to annotate the injection point with a custom annotation which is used when constructing the prototype bean. 但是,我确实希望每次都有一个稍微不同的bean,所以我希望能够使用在构造原型bean时使用的自定义注释来注释注入点。

The problem is, how do I find out what annotations are on the injection point? 问题是,我如何找出注入点上的注释?

Here's some code to see what I want to achieve: 这里有一些代码可以看到我想要实现的目标:

@Component
public class X {
    @Inject
    @CustomAnnotation("Hi")
    private PrototypeBean bean;
}

Where PrototypeBean is provided by a bean method: PrototypeBean由bean方法提供:

@Bean
public PrototypeBean prototypeBean(CustomAnnotation customAnnotation) {
    return new PrototypeBean(customAnnotation);
}

The idea is here that everywhere this PrototypeBean is injected, a new instance is created which behaves slightly differently based on the value of CustomAnnotation. 这里的想法是,在注入PrototypeBean的任何地方,都会创建一个新实例,它根据CustomAnnotation的值略有不同。

I know you can do this using the ApplicationContext (well, passing extra parameters that is, not annotations), but I'd like to keep it light-weight with simple annotations. 我知道你可以使用ApplicationContext做到这一点(好吧,传递额外的参数,而不是注释),但我想用简单的注释保持它的轻量级。

Perhaps what you need is a custom BeanPostProcessor . 也许您需要的是自定义BeanPostProcessor Section "3.2 Data Access" in this blog post, " A Spring Custom Annotation for a Better DAO " looks very similar to what you're trying to do. 本博文中的“3.2数据访问”一节“ 更好的DAO的Spring自定义注释 ”看起来与您尝试做的非常相似。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM