Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @Value Spring Annotation with Groovy

I have a groovy class where I wan to autowire a property value.

Eg:

public @Value("${valueA}" ) String valueA; 

With the addition of the the property-placeholder in my appliction context

<context:property-placeholder location="classpath:spring/app.properties" /> 

The app.properties has a value set for "valueA" so in theory this should populate the String valueA in my class at runtime.

This setup works perfectly if I use a java class but not if I use a groovy class.

I get a compile error:

Error: expected '$valueA' to be an inline constant of type java.lang.String in @org.springframework.beans.factory.annotation.Value
Error: Attribute 'value' should have type 'java.lang.String'; but found type 'java.lang.Object' in @org.springframework.beans.factory.annotation.Value

I just want to know if the above syntax is correct when using a groovy class and if not what is the correct syntax for autowiring the @Value parameter at runtime.

like image 826
Dion Avatar asked Apr 13 '11 11:04

Dion


People also ask

Where can I use @value annotation?

@Value is a Java annotation that is used at the field or method/constructor parameter level and it indicates a default value for the affected argument. It is commonly used for injecting values into configuration variables - which we will show and explain in the next part of the article.

What is the use of @value annotation in spring?

Spring @Value annotation is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. Spring @Value annotation also supports SpEL.

Can we use @value in interface?

No, this is not (directly) possible. The default value of an annotation property must be a compile-time constant.

What does @value do in spring boot?

One of the most important annotations in spring is @Value annotation which is used to assign default values to variables and method arguments. We can read spring environment variables as well as system variables using @Value annotation. It also supports Spring Expression Language (SpEL).


1 Answers

Use single quotes, ie.

public @Value('${valueA}') String valueA 
like image 138
sourcedelica Avatar answered Oct 19 '22 22:10

sourcedelica