shantanu
shantanu

Reputation: 2008

how to autowire @bean classes

I have following @Configuration class

@Configuration
public class SomeClass {
    @Bean
    public BeanClass get() {
        return new BeanClass()
    }
}

Now I want to autowire BeanClass in some other class

public class SomeClass2 {
    @Autowired
    BeanClass beanCLass
}

Currently beanClass is coming null.
What and how exactly I need to tell spring for this autowiring.

Upvotes: 1

Views: 890

Answers (2)

MariuszS
MariuszS

Reputation: 31557

According to Spring documentation

By default, the bean name will be that of the method name

get is your bean name, try with this configuration:

@Configurtion
public class SomeClass {
    @Bean
    public BeanClass beanCLass() {
        return new BeanClass()
    }
}

Bean

@Component
public class SomeClass2 {
    @Autowired
    BeanClass beanCLass
}

Upvotes: 1

Amit Parashar
Amit Parashar

Reputation: 1457

Your SomeClass2 must be a spring bean. Annotate SomeClass2 with @Component.

Upvotes: 0

Related Questions