PixelMaster
PixelMaster

Reputation: 954

Autowiring values using SpEL: referencing beans by type

I currently want to automagically set an object's / bean's ID; I got it working so far, but it requires specifying the exact bean name of the counter I'm referencing. 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.


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()


Is it possible to reference beans by type instead of by name when using SpEL in @Value annotations (or elsewhere)?

Upvotes: 0

Views: 1737

Answers (1)

Gary Russell
Gary Russell

Reputation: 174664

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. 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).

Upvotes: 1

Related Questions