简体   繁体   English

使用SpEL自动装配值:按类型引用bean

[英]Autowiring values using SpEL: referencing beans by type

I currently want to automagically set an object's / bean's ID; 我目前想自动设置对象的/ bean的ID; I got it working so far, but it requires specifying the exact bean name of the counter I'm referencing. 到目前为止,我已经可以使用它了,但是它需要指定我要引用的计数器的确切bean名称。 Here's how: 这是如何做:

@Autowired
@Value("#{ counter.next() }")
public void setId(int id) {
    this.id = id;
}

My config has a counter: 我的配置有一个计数器:

@Bean
public Counter counter() {
    return new Counter();
}

The object that needs an ID set is also defined in the same config as a prototype-scoped bean. 还需要在与原型作用域的bean相同的配置中定义需要ID集的对象。


Now while this works fine so far, what I would like to do is to autowire the counter by type, not by name. 现在,尽管到目前为止一切正常,但我想做的是按类型而不是按名称自动连接计数器。 I tried the following, but it didn't work: 我尝试了以下操作,但没有成功:

@Value("#{ T(packagepath.Counter).next() }")

I'm assuming it's only intended for static methods, or at least I got it working by making my counter static - only problem is I don't want that. 我以为它仅适用于静态方法,或者至少我通过使计数器为静态来使其工作-唯一的问题是我不希望这样做。 Side note: the spring doc is using this format for calling Math.random() : T(java.lang.Math).random() 旁注:spring文档正在使用这种格式来调用Math.random()T(java.lang.Math).random()


Is it possible to reference beans by type instead of by name when using SpEL in @Value annotations (or elsewhere)? @Value注释(或其他地方)中使用SpEL时,是否可以按类型而不是按名称引用bean?

This works... 这有效...

@SpringBootApplication
public class So52118412Application {

    public static void main(String[] args) {
        SpringApplication.run(So52118412Application.class, args);
    }

    @Value("#{beanFactory.getBean(T(com.example.Counter)).next()}")
    int n;

    @Bean
    public ApplicationRunner runner() {
        return args -> System.out.println(n);
    }
}

@Component
class Counter {

    int i;

    public int next() {
        return ++i;
    }

}

To explain further; 进一步解释; the root object for #{...} is a BeanExpressionContext which allows access to any bean by name. #{...}的根对象是BeanExpressionContext ,它允许按名称访问任何bean。 However, the BeanExpressionContext also has a property beanFactory , which allows you to reference it, and perform any operation on it (such as getting a bean by its type). 然而, BeanExpressionContext还具有属性beanFactory ,它允许你引用它,并在其上进行任何操作(例如,通过它的类型得到一个豆)。

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

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