@ComponentScan#includeFilters can be used to scan classes which are not annotated with @Component and other stereotype annotation. It can be done by specifying a Filter with type as FilterType#ASSIGNABLE_TYPE and classes as non component classes to be scanned. For example:
@ComponentScan(includeFilters = @ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE, classes = {OrderService.class}))
Example
A non component class
package com.logicbig.example;
public class OrderService {
public void placeOrder(String item) {
System.out.printf("Retail order placed. Item: %s%n", item);
}
}
A component class
package com.logicbig.example;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class Buyer {
@Autowired
private OrderService orderService;
public void buySomething() {
orderService.placeOrder("Laptop");
}
}
Main class
package com.logicbig.example;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
@Configuration
@ComponentScan(includeFilters = @ComponentScan.Filter(
type = FilterType.ASSIGNABLE_TYPE, classes = {OrderService.class}))
public class OnlineOrderApp {
public static void main(String... strings) {
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(OnlineOrderApp.class);
System.out.println("-- Spring container started and is ready --");
Buyer buyer = context.getBean(Buyer.class);
buyer.buySomething();
}
}
Output
-- Spring container started and is ready -- Retail order placed. Item: Laptop
Example Project
Dependencies and Technologies Used:
spring-context 6.1.2 (Spring Context) Version Compatibility: 4.2.0.RELEASE - 6.1.2Version List
×
Version compatibilities of spring-context with this example: