Search code examples
javaspringspring-annotations

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.


Solution

  • 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
    }