Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude a particular class from Spring Component scan while writing Spring Integration Test

My classes are..

lies in src/intregation-test/java

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = StoreOrderFulfillmentApplication.class)
  @ActiveProfiles("Test")
  public class OrderCreationIntregationTest {

@Autowired
private TestRestTemplate restTemplate;

@MockBean
private OrderRepository orderRepository;

@MockBean
private OrderLineItemRepository orderLineItemRepository;

@MockBean
private InternalEventPublisher internalEventPublisher;

@SuppressWarnings("unchecked")
@Before
public void setup() {
    Mockito.when(orderRepository.findByOfsReferenceId("OFS:GMO:Z100002062-99")).thenReturn(null);
    OrderEntity savedOrder = new OrderEntity();
    savedOrder.setOrderId(1023);
    Mockito.when(orderRepository.save(Mockito.any(OrderEntity.class))).thenReturn(savedOrder);
    Iterable<OrderLineItemEntity> orderLineItemList = prepareOrderLineItemEntityIterable();
    Mockito.when(orderLineItemRepository.save(Mockito.any(Iterable.class))).thenReturn(orderLineItemList);
}

@Test
public void test() throws ParseException {
    FulfillmentOrder fulfillmentOrderRequestVO = new FulfillmentOrder();
    fulfillmentOrderRequestVO = buildFulfillmentOrder();
    String myMessage = "Order Created";
    ResponseEntity<ResponseOrderMessage> responseEntity = restTemplate.postForEntity("/fulfillmentprocessor/orders",
            fulfillmentOrderRequestVO, ResponseOrderMessage.class);
    ResponseOrderMessage responseOrderMessage = responseEntity.getBody();
    assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
    assertEquals(myMessage, responseOrderMessage.getMessage());
}

lies in src/main/java

@SpringBootApplication
public class StoreOrderFulfillmentApplication {

public static void main(String[] args) {
    SpringApplication.run(StoreOrderFulfillmentApplication.class, args);
}
}

Now the problem is I wanted to exclude a class from being get component scanned.my this class contains the dependency for apache Kafka. if this class loads while container start up it start looking for kafka running instances. so while running Intregation test I will not be starting my Kafka server,so I wanted to run Intregation test making kafka shutdown.

This I can achieved by adding one line code in StoreOrderFulfillmentApplication class

@ComponentScan(basePackages = "com.tesco.store.order.fulfillment.processor", excludeFilters = @Filter(type = FilterType.ASSIGNABLE_TYPE, classes = OrderReceiveEventConfiguration.class))

by addding this line of code StoreOrderFulfillmentApplication class it is excluding OrderReceiveEventConfiguration class from being get component scanned.

now the problem is I not suppose add any test configuration changes in the main code. so I am struggling to do the same exclusion from src/intregation-test/java source folder, is their some way that I can exclude this particular class during container startup code.

but it should not affect my main class code means code inside src/main/java

Any help is Appreciated..

like image 522
Shobhit Pal Avatar asked Feb 15 '17 09:02

Shobhit Pal


People also ask

How do I exclude a particular class in Spring boot?

If the class is not on the classpath, you can use the excludeName attribute of the annotation and specify the fully qualified name instead. Finally, you can also control the list of auto-configuration classes to exclude by using the spring. autoconfigure. exclude property.

How do I disable component scan?

To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.

What is exclude in @SpringBootApplication?

exclude – To exclude specific auto-configuration classes. scanBasePackages – A list of base packages to scan for spring components and beans.

Can we exclude any package without using then basePackages filter Yes No?

Yes. It is possible to exclude package without using the basePackages filter by simply using the exclude attribute while using the @SpringBootApplication annotation.


1 Answers

You can make use of @Conditional as shown below.

  • In application.properties introduce a property say kafka.enabled.
  • Annotate the OrderReceiveEventConfiguration with @Conditional(PropertyCondition.class)
  • Depending on kafka.enabled value viz. true (for normal run) or false (for testing) the OrderReceiveEventConfiguration will be picked up or ignored respectively without changing the code.

Let know in comments in case any more information is required.


Except main @conditional annotation there are set of similar annotation to be used for different cases.

Class conditions

The @ConditionalOnClass and @ConditionalOnMissingClass annotations allows configuration to be included based on the presence or absence of specific classes.

E.g. when OObjectDatabaseTx.class is added to dependencies and there is no OrientWebConfigurer bean we create the configurer.

@Bean
@ConditionalOnWebApplication
@ConditionalOnClass(OObjectDatabaseTx.class)
@ConditionalOnMissingBean(OrientWebConfigurer.class)
public OrientWebConfigurer orientWebConfigurer() {
    return new OrientWebConfigurer();
}

Bean conditions

The @ConditionalOnBean and @ConditionalOnMissingBean annotations allow a bean to be included based on the presence or absence of specific beans. You can use the value attribute to specify beans by type, or name to specify beans by name. The search attribute allows you to limit the ApplicationContext hierarchy that should be considered when searching for beans.

See the example above when we check whether there is no defined bean.

Property conditions

The @ConditionalOnProperty annotation allows configuration to be included based on a Spring Environment property. Use the prefix and name attributes to specify the property that should be checked. By default any property that exists and is not equal to false will be matched. You can also create more advanced checks using the havingValue and matchIfMissing attributes.

@ConditionalOnProperty(value='somebean.enabled', matchIfMissing = true, havingValue="yes")
@Bean 
public SomeBean someBean(){
}

Resource conditions

The @ConditionalOnResource annotation allows configuration to be included only when a specific resource is present.

@ConditionalOnResource(resources = "classpath:init-db.sql") 

Web application conditions

The @ConditionalOnWebApplication and @ConditionalOnNotWebApplication annotations allow configuration to be included depending on whether the application is a 'web application'.

@Configuration
@ConditionalOnWebApplication
public class MyWebMvcAutoConfiguration {...}

SpEL expression conditions

The @ConditionalOnExpression annotation allows configuration to be included based on the result of a SpEL expression.

@ConditionalOnExpression("${rest.security.enabled}==false")
like image 92
Bond - Java Bond Avatar answered Oct 23 '22 08:10

Bond - Java Bond