3

I have created a service:

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

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

and a component

  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();
        }
      }

I added the component-scan tag in my application context

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

Why the exchangeService is null? (although it works when I inject it into a @Controller).

Nathan Hughes
  • 94,330
  • 19
  • 181
  • 276
blue
  • 525
  • 1
  • 8
  • 20

2 Answers2

3

Since this is a DTO, I guess you do something like ProductDTO productDTO = new ProductDTO();.
So annotated @Autowired ExchangeService is null because Spring doesn't know about the copy of ProductDTO that you created with new and didn't know to autowire it.

Some more info

Olezt
  • 1,638
  • 1
  • 15
  • 31
2

You run this code:

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

in a constructor, that is not autowired. No wonder it can not autowire bean, since it is not a bean itself. The idea of IoC is that Spring Container is creating beans itself. If you want Spring to use a specific constructor, you have to Autowire it like this:

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();
    }
  }
Kawior
  • 21
  • 1