1

I have a service interface called ABCService and its implementation called ABCServiceImpl.

ABCService.class

package com.abc.service.ABCService;

public interface ABCService{
    //interface methods
}

ABCServiceImpl.class

package com.abc.service.ABCServiceImpl; 

@Service
public class ABCServiceImpl implements ABCService{
     // implemented methods
}

XYZ.class

package com.abc.util.XYZ;

public class XYZ{

  @Autowired
  ABCService abcService;

  //methods
}

application-context.xml

<context: annotation-config>
<context: component-scan base-package="com.abc.service, com.abc.util"/>

But when I am trying to use the autowired ABCService in class XYZ to access methods in interface ABCService, I get a null pointer exception. I then removed the @Service annotation from ABCServiceImpl & added the implentation file in the application-context.xml as a bean & created a bean for class XYZ and gave reference of ABCServiceImpl's bean to bean of class XYZ ; it solved the issue

application-context.xml

<bean id="abcService" class="com.abc.service.ABCServiceImpl" />

<bean id="xyz" class="com.abc.util.XYZ" >
    <property name="abcService" ref="abcService"></property>
</bean>

but I want to use the @Service annotation itself without explicitly defining a bean in application-context.xml. How do I do it?

Akash Raveendran
  • 559
  • 1
  • 9
  • 22
  • Is it a requirement that class XYZ is outside the package scanned services? – Adam Jun 02 '16 at 13:55
  • @Adam : yes XYZ is a utility class and I do not want to put that class in the service package. Hence the XYZ class will be in com.abc.util package – Akash Raveendran Jun 02 '16 at 14:02

1 Answers1

0

If you want to autowire beans without package scanning, or defining them in XML, then your only option is to do it programmatically using the Spring API...

This is possible using

XYZ bean = new XYZ();
context.getAutowireCapableBeanFactory().autowireBean(bean);

Also if you want any @PostConstruct methods to be called, use

context.getAutowireCapableBeanFactory().initializeBean(bean, null);
Adam
  • 35,919
  • 9
  • 100
  • 137