简体   繁体   中英

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?

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.

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.

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/>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM