繁体   English   中英

@Autowire注解问题

[英]Problems with @Autowire annotation

在我的A类中,我正在自动装配具有@Service批注的B类。 在我的B类中,我正在自动装配C类,并在B类中的@Transactional方法内使用对该类的引用。

而且似乎自动接线没有任何作用,因为我得到了java.lang.NullPointerException

A类示例:

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

B级

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

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

}

有帮助吗?

如果要使用@Autowired注释为您进行Spring接线,则需要注册适当的BeanPostProcessor来提供帮助。 您可以让Spring通过在Spring配置中包含以下元素来为您完成此操作:

<context:annotation-config/>

有关更多信息,请参阅Spring 3.0文档中的3.9节

另外,由于似乎您使用的是@Component型注释( @Component@Service @Controller@Service @Controller ),因此您可能正在尝试放弃Spring XML接线(或减少接线)。 您将需要确保在Spring XML中包括component-scan元素。

注意:如果要包含component-scan ,则无需使用annotation-config元素。

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

有关更多信息,请参阅Spring 3.0文档中的3.10节

确保以某种方式配置了DAO ...无论是使用xml配置中的注解(@ Service,@ Component,@ Repository),还是通过其他方式进行配置。

如果这样做没有帮助,我们将需要更多信息。

服务等级

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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