Kanagavelu Sugumar
Kanagavelu Sugumar

Reputation: 19260

NullPointerException: @Autowired does not set field

I am learning SPRING and this is not web application code; I am getting NLP while using @Autowired annotation in field level.

Q1) Please help what is wrong?
Q2) If i have @Scope annotation at the class level; do i still need at XML bean level?

@Controller
@Scope(value = BeanDefinition.SCOPE_SINGLETON)
public class StreamingController implements psConsolePortListener.Implementation{

    @Autowired
    @Qualifier("scMgr")
    private StreamingControllerManager streamingMgr = null;

    public static void main(String[] args) {
        logger.info("StreamingController testing");
        XmlBeanFactory factory = new XmlBeanFactory (new ClassPathResource(BEAN_FILE)); 
        StreamingController obj = (StreamingController) factory.getBean("streamingController"); 
        obj.streamingMgr.test();
    }

}


@Service
@Scope(value = BeanDefinition.SCOPE_SINGLETON)
@Qualifier("scMgr")
public class StreamingControllerManager {
    /** Logger */
    private static final Logger logger = LoggerFactory.getLogger(StreamingControllerManager.class);

    private StreamingControllerManager(){
        logger.info("StreamingControllerManager is called!!");
    }

    public void test(){
        logger.info("StreamingControllerManager test!!");
    }
}


<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <context:annotation-config />
    <context:component-scan base-package="com.xxx.streamingController"/>
    <bean id="scMgr" class="com.xxx.streamingController.StreamingControllerManager"> 
    </bean>
    <bean id="streamingController" class="com.xxx.streamingController.StreamingController"> 
    </bean>
</beans>

Output:

Exception in thread "main" java.lang.NullPointerException
        at com.pactolus.streamingController.StreamingController.main(

Upvotes: 0

Views: 134

Answers (1)

M. Deinum
M. Deinum

Reputation: 124526

Use an ApplicationContext instead of a BeanFactory.

public static void main(String[] args) {
    logger.info("StreamingController testing");
    ApplicationContext ctx = new ClassPathXmlApplicationContext(BEAN_FILE);
    StreamingController obj = (StreamingController) ctx.getBean("streamingController"); 
    obj.streamingMgr.test();
}

Also remove <context:annotation-config /> that is already impllied by <context:component-scan /> and remove the bean declarations. You are using component-scanning so no need to declare the beans.

Basically leaving you with.

<?xml version="1.0" encoding="UTF-8"?>
<beans>
    <context:component-scan base-package="com.xxx"/>
</beans>

Upvotes: 1

Related Questions