1 year ago
#307226
bodrin
Calling a @Bean annotated method in Spring java configuration with dummy param values
I have an application with a huge amount of beans and I have a problem - I have tried to isolate it here in this example but unfortunately it works as expected but still I'm posting the example as I would like to know whether my expectation is correct:
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
@Configuration
@PropertySource("classpath:foo.properties")
public class PropertiesWithJavaConfig {
static class Service1 {
private final String fooParam;
public Service1(String fooParam) {
this.fooParam = fooParam;
}
}
static class Service2 {
public Service2(Service1 service1) {
}
}
@Bean
public Service2 service2() {
System.out.println("create service2");
Service1 s1 = service1(null);
return new Service2(s1);
}
@Bean
public Service1 service1(@Value("${foo}") String fooParam) {
System.out.println("create service1: fooParam=" + fooParam);
return new Service1(fooParam);
}
public static void main(String[] args) {
ApplicationContext ctx = new AnnotationConfigApplicationContext(PropertiesWithJavaConfig.class);
}
}
Executing the above gives me:
create service2
create service1: fooParam=bar
foo.properties file contents are:
foo=bar
So as you can see the output - spring magic does work - even that service2 bean method calls service1 with null argument - it receives the right argument which is taken from the properties file.
In contrast in my application the bean method is called with null argument instead with the proper value obtained from the properties file. This seems like a bug to me? What do you think?
I have made a workaround by replacing the param as a field :
...
@Value("${foo}") String fooParam;
@Bean
public Service1 service1() {
System.out.println("create service1: fooParam=" + fooParam);
return new Service1(fooParam);
}
...
java
spring
cglib
0 Answers
Your Answer