Richard
Richard

Reputation: 6116

Writing JavaConfig inter-bean dependency with parameter args

I am trying to write these two beans in my configuration class:

@Bean
public Foo2 foo2() {
    return new Foo2(foo1("test"));
}

@Bean
public Foo1 foo1(String name) {
    return new Foo1(name);
}

But I get an error marker under name saying Could not autowire. No beans of String type found. Any idea how to wire these beans up properly?

Upvotes: 1

Views: 278

Answers (1)

roblovelock
roblovelock

Reputation: 1981

Spring needs to know whare to get the name property from. You can use the @Value annotation.

Name with a value of "Name"

@Value("Name")

Name with a value loaded from a properties file

@Value("${name.property}")

Name with a value loaded from a properties file or a default of "Name" is no property is found.

@Value("${name.property:Name}")

The full solution would be:

@Bean
public Foo2 foo2(Foo1 foo1) {
    return new Foo2(foo1);
}

@Bean
public Foo1 foo1(@Value("${name.property:test}") final String name) {
    return new Foo1(name);
}

UPDATE

If you want multiple instances of the bean with different name properties then you will need to create multiple methods and autowire using a @Qualifier:

@Bean
public Foo2 bar2(@Qualifier("bar1") Foo1 bar1) {
    return new Foo2(bar1);
}

@Bean
public Foo2 foo2(@Qualifier("foo1") Foo1 foo1) {
    return new Foo2(foo1);
}

@Bean
public Foo1 foo1(@Value("test foo1") final String name) {
    return new Foo1(name);
}

@Bean
public Foo1 bar1(@Value("test bar1")  final String name) {
    return new Foo1(name);
}

If you aren't using each Foo1 instance as a singleton that needs injecting into multiple locations then there is no need to manage it using spring. If this is the case then you can remove the @Bean annotation:

@Bean
public Foo2 foo2() {
    return new Foo2(foo1("test"));
}

@Bean
public Foo2 bar2() {
    return new Foo2(foo1("test bar2"));
}

public Foo1 foo1(final String name) {
    return new Foo1(name);
}

Upvotes: 2

Related Questions