【问题标题】:Problems with @Autowire annotation@Autowire 注解的问题
【发布时间】:2017-12-20 18:17:40
【问题描述】:

在我的 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);
   }

}

有什么帮助吗?

【问题讨论】:

  • 您可以发布您的 context.xml(或等效)内容吗?

标签: java spring spring-mvc


【解决方案1】:

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

<context:annotation-config/>

查看Section 3.9 in the Spring 3.0 Documentation 了解更多信息。

此外,由于您似乎正在使用构造型注释(@Component@Service@Controller),您可能正试图放弃 Spring XML 连接(或减少它)。您需要确保在 Spring XML 中包含组件扫描元素。

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

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

查看Section 3.10 in the Spring 3.0 Documentation 了解更多信息。

【讨论】:

    【解决方案2】:

    确保您的 DAO 以某种方式配置...无论是使用注释(@Service、@Component、@Repository)、在 xml 配置中还是通过其他方式。

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

    【讨论】:

      【解决方案3】:

      服务类

      @Service
      public Class serviceImpl implements MyService {
         @Autowired
         private DAOInterface dao;
         //nullpointer
      
         @Transactional
         public String getItem(){
          return dao.getItem(2);
         }
      
      }
      

      spring-servlet.xml

      &lt;context:annotation-config/&gt;

      【讨论】:

      • 请解释您在做什么,而不是仅仅发布答案。文档会很棒!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-20
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多