Gandalf StormCrow
Gandalf StormCrow

Reputation: 26212

Problems with @Autowire annotation

In my Class A, I'm auto-wiring Class B which has @Service annotation. In my Class B I'm auto-wiring class C and using reference to that class inside @Transactional method in class B.

And it appears that Auto-Wiring didn't do anything because I get java.lang.NullPointerException

Example of Class A :

@Controller
public Class controller{
   @Autowired
   private MyService myservice;
}

Class B

@Service
public Class serviceImpl{
   @Autowired
   private DAOInterface dao;
   //nullpointer

   @Transactional
   public String getItem(){
    return dao.getItem(2);
   }

}

Any Help?

Upvotes: 1

Views: 1764

Answers (3)

Harshad
Harshad

Reputation: 1

Service Class

@Service
public Class serviceImpl implements MyService {
   @Autowired
   private DAOInterface dao;
   //nullpointer

   @Transactional
   public String getItem(){
    return dao.getItem(2);
   }

}

spring-servlet.xml

<context:annotation-config/>

Upvotes: 0

smp7d
smp7d

Reputation: 5032

Make sure you're DAO is configured in some way...whether it be with an annotation (@Service, @Component, @Repository), in the xml configuration, or through some other means.

If this doesn't help, we will need more information.

Upvotes: 1

nicholas.hauschild
nicholas.hauschild

Reputation: 42834

If you want to use the @Autowired annotation to do your Spring wiring for you, you need to register the proper BeanPostProcessor's to assist. You can have Spring do this for you by including the following element in your Spring configuration:

<context:annotation-config/>

Take a look at Section 3.9 in the Spring 3.0 Documentation for more information on this.

Also, since it appears that you are using the stereotype annotations (@Component, @Service, @Controller), you may be trying to forego Spring XML wiring (or reducing it). You will need to make sure that you are including the component-scan element in your Spring XML.

NOTE: If you are including component-scan, then you should not need to use the annotation-config element.

<context:component-scan base-package="your.package.name"/>

Take a look at Section 3.10 in the Spring 3.0 Documentation for more information on this.

Upvotes: 4

Related Questions