Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Methods/functions cannot be directly invoked in the @Value-annotation, but you can use SpEL (Spring Expression Language) to call methods or functions indirectly.

For example, if you have a class with a method that returns a string value:

public class MyConfig {
    public String getDatabaseUrl() {
        return "jdbc:mysql://localhost/mydatabase";
    }
}

You can use SpEL to call the getDatabaseUrl() method and use its return value in the @Value-annotation:

@Configuration
public class AppConfig {
    @Value("#{myConfig.databaseUrl}")
    private String databaseUrl;

    ...
}

Here, the #{} syntax indicates that SpEL should be used to evaluate the expression within the curly braces. The myConfig is a reference to an instance of MyConfig that Spring manages. The dot notation is used to call the getDatabaseUrl() method on that instance. The evaluated value of the expression is then assigned to the databaseUrl field.

Note that in order for this to work, the MyConfig class must be annotated as a bean, either with the @Component or @Configuration annotation.