java - 使用 SpEL Autowiring 值 : referencing beans by type

标签 java spring spring-el spring-bean

我目前想要自动设置对象/bean 的 ID;到目前为止我已经可以正常工作了,但是它需要指定我引用的计数器的确切 bean 名称。方法如下:

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

我的配置有一个计数器:

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

需要 ID 集的对象也在与原型(prototype)范围 bean 相同的配置中定义。

<小时/>

虽然到目前为止效果很好,但我想做的是按类型而不是按名称自动连接计数器。我尝试了以下方法,但没有成功:

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

我假设它仅适用于静态方法,或者至少我通过使计数器静态来使其工作 - 唯一的问题是我不希望这样。 旁注:spring 文档使用此格式调用 Math.random(): T(java.lang.Math).random()

<小时/>

@Value 注释(或其他地方)中使用 SpEL 时,是否可以通过类型而不是名称来引用 bean?

最佳答案

这有效...

@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;
    }

}

进一步解释; #{...} 的根对象是一个 BeanExpressionContext,它允许通过名称访问任何 bean。但是,BeanExpressionContext 还有一个属性beanFactory,它允许您引用它,并对其执行任何操作(例如通过其类型获取 bean)。

关于java - 使用 SpEL Autowiring 值 : referencing beans by type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52118412/

相关文章:

xml - 从 .properties 文件中访问 SpEL 表达式中的属性

java - Jboss 标准输出时间戳

java - JTable 以不希望的顺序对 int 进行排序

java - -Dspring.profiles.active 在条件下无法识别

java - Spring文件上传 - 得到预期的MultipartHttpServletRequest : is a MultipartResolver configured?错误

spring - 将 spring mvc 项目部署到 tomcat 时,有什么方法可以自动重写 URL?

spring-boot - 在@Document indexName 中使用的 SpEL 与 spring 数据 elasticsearch 和 spring boot 没有被解析

java - 公开 JSP 文件中未使用的属性 (Spring)

java - php检查数据库中两个字段是否存在,使用JSON

java - 从 jndi 注入(inject)属性