MRK187
MRK187

Reputation: 1605

Java class xml vs java bean autowiring

In xml defined beans you can define two classes like this

<bean id="classA" class="ex.ClassA"/>

<bean id="classB" class="ex.classB"/>

Then in your java implementation you can autowire the constructor of one of the classes in example

public class ClassA {
@autowired
public(ClassB classB){
this.classB = classB;
}

Now how does one do that with java config beans since in example

@Bean
public ClassA classA(){
return new ClassB();
}

@Bean
public ClassB classB(){
return new ClassB()
}

the compiler would warn that Class a does not have any such constructor, how does one do that in java, with autowiring?

Thanks all

Upvotes: 0

Views: 967

Answers (2)

Don Bottstein
Don Bottstein

Reputation: 1660

See http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-java-injecting-dependencies

Note that the ClassB bean is implicitly a singleton. The use of the annotation @Configuration on the Config class ensures that Spring returns the singleton instance of the ClassB bean in the classB() call.

@Configuration
public class Config {
    @Bean
    public ClassA classA(){
        return new ClassA( classB() );
    }

    @Bean
    public ClassB classB(){
        return new ClassB();
    }
}

Or you may prefer this approach (Spring 4.2.1+ required)

@Configuration
@Import(ClassA.class)
public class Config {
    @Bean
    public ClassB classB(){
        return new ClassB();
    }
}

@Component
public class ClassA {
    @Autowired
    public ClassA(ClassB classB) {
      ...
    }
}

Upvotes: 1

Pass the beans you want as parameters to the @Bean method, or use component scanning to create the dependent bean implicitly.

Upvotes: 0

Related Questions