Search code examples
springspring-annotations

Spring Configuration with annotations @Autowired not working - step by step


I have performed this steps in order to use annotation based configuration:

a) beans.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context-3.2.xsd">

    <context:annotation-config/>

    <context:component-scan base-package="test.*"/>

</beans>

b) then I have this component:

package test;
@Component
public class InMemoryUserService implements UserService 

c) then I try to use autowire:

@Autowired
private UserService userService;

and in runtime userService is null.

Basic stuff is set up properly (like dependencies etc.) because in first version of the test app I was using xml based configuration and it was working smoothly.

And this is a class that uses autowireing:

public class DemoApplication {

    @Autowired
    private UserService userService;

    public DemoApplication() {
    }


    public static void main(String[] args) {

        DemoApplication da = new DemoApplication();
        da.userService.getUserByEmail("blabla@gmail.com");
    }
}

Is there anything else I'm missing?


Solution

  • That is because -

    • DemoApplication is not a spring managed bean. Make it spring managed by adding @Component similar to UserService.
    • Use spring bean factory or application context, say ClasspathXMLApplicationContext, to get the DemoApplication instead of new operator.