@Component always null in spring boot

@Component always null in spring boot

Problem Description:

I have two classes which are annotated as @Component

@Component
public class ClientMapper {
  public Client convert(ClientEntity clientEntity) {
    Client client = new Client();
    BeanUtils.copyProperties(clientEntity, client);
    return client;
  }

  public ClientEntity convert(Client client) {
    ClientEntity clientEntity = new ClientEntity();
    BeanUtils.copyProperties(client, clientEntity);
    return clientEntity;
  }
}
@Component
public class OrderMapper {
  public Order convert(OrderEntity orderEntity) {
    Order order = new Order();
    BeanUtils.copyProperties(orderEntity, order);
    return order;
  }

  public OrderEntity convert(Order order) {
    OrderEntity orderEntity = new OrderEntity();
    BeanUtils.copyProperties(order, orderEntity);
    return orderEntity;
  }
}

I injected them into different services

@Service
@AllArgsConstructor
public class ClientServiceImpl implements ClientService {

  private final ClientMapper clientMapper;
  private final ClientRepository clientRepository;
@Service
@AllArgsConstructor
public class OrderServiceImpl implements OrderService {

  private final OrderMapper orderMapper;
  private final OrderRepository orderRepository;
  private final OrderNumberRepository orderNumberRepository;

But all time my mappers is null. I don’t create new Object of them using new command. Also with my repository interfaces everything is fine, so my way to inject my comments(@AllArgsContrustor) works correct.
screen of code where you can see that mapper is null
Little note, I have tests classes where I used @InjectMocks on my services classes. Can it be that my error occupied because of this annotation?

@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {
  @Mock
  private OrderRepository orderRepository;
  @InjectMocks
  private OrderServiceImpl orderService;

Solution – 1

You are using MockitoExtension, spring won’t create component of OrderMapper.
If you need actual implementation. Use @Spy annotation of MockitoExtension.

@ExtendWith(MockitoExtension.class)
public class OrderServiceTest {
  @Mock
  private OrderRepository orderRepository;
  @Spy
  private OrderMapper orderMapper = new OrderMapper(); // Note: new OrderMapper() is optional as you have No Argument Constructor
  @InjectMocks
  private OrderServiceImpl orderService;

Or as a practice @Mock is always best way to go instead of @Spy incase of Unit test.

Rate this post
We use cookies in order to give you the best possible experience on our website. By continuing to use this site, you agree to our use of cookies.
Accept
Reject