Spring:组件中的自动服务为null

时间:2018-01-02 15:04:25

标签: spring service nullpointerexception annotations autowired

我创建了一项服务:

  package tn.ett.medial.service;
   @Service
   public class ExchangeService {
     private Currency EURCurrency;

     public Currency getEURCurrency() {
          ....
       return EURCurrency;
     }

和一个组件

  package tn.ett.medial.utils.dto;
    @Component
    public class ProductDTO implements Serializable {

        @Autowired
        ExchangeService exchangeService;

        public ProductDTO() {
        }

        public ProductDTO(Product product){

            System.out.println("service****" + exchangeService);
            Currency EURCurrency = exchangeService.getEURCurrency();
        }
      }

我在应用程序上下文中添加了组件扫描标记

 <context:component-scan base-package="tn.ett.medial" />

为什么exchangeService为null? (虽然它在我将它注入@Controller时有效。)

2 个答案:

答案 0 :(得分:2)

由于这是一个DTO,我猜你会做ProductDTO productDTO = new ProductDTO();之类的事情 因此,注释的@Autowired ExchangeService为空,因为Spring并不知道您使用new创建的ProductDTO副本,并且不知道自动装配它。

Some more info

答案 1 :(得分:1)

您运行此代码:

        System.out.println("service****" + exchangeService);
        Currency EURCurrency = exchangeService.getEURCurrency();

在构造函数中,不是自动装配的。难怪它不能自动装配bean,因为它本身不是bean。 IoC的想法是Spring Container本身正在创建bean。 如果你想让Spring使用特定的构造函数,你必须像这样自动装配它:

package tn.ett.medial.utils.dto;
@Component
public class ProductDTO implements Serializable {

    private final ExchangeService exchangeService;

    public ProductDTO() {
    }

    @Autowired
    public ProductDTO(Product product, ExchangeService exchangeService){
        this.exchangeService = exchangeService;
        System.out.println("service****" + exchangeService);
        Currency EURCurrency = exchangeService.getEURCurrency();
    }
  }