It’s a fairly common task as a Java developer to convert from a List to an Array or from an Array to a list.

In one of my previous post, I discussed about converting Map to List.

Like many things in Java, there is often more than one way to accomplish a task. In this post, I’ll discuss various approaches of converting data between List objects and arrays.

Converting List to Array

The List interface comes with a toArray() method that returns an array containing all of the elements in this list in proper sequence (from first to last element). The type of the returned array is that of the array that you pass as parameter.

A ListToArrayConvertor class that converts a List to an array is this.

ListToArrayConvertor.java

I have written a JUnit test case to test the convert() method.

If you are new to JUnit, I would suggest going through my series of posts on JUnit.

The test class, ListToArrayConvertorTest is this.

ListToArrayConvertorTest.java

The test case calls the convert() method of the ListToArrayConvertor class and asserts two things. First it asserts that the array returned by the convert() method is not null. Second it asserts that the array contains the same number of elements as that of the list passed to the convert() method.

Converting List to Array using Java 8 Stream

With the introduction of Streams in Java 8, you can convert a List into a sequential stream of elements. Once you obtain a stream as a Stream object from a collection, you can call the Stream.toArray() method that returns an array containing the elements of this stream.

The code to convert a List to an array using stream is this.

The JUnit test code is this.

Converting List to Primitive Array

When you call the List.toArray() method, you get wrapper arrays, such as Integer[], Double[], and Boolean[]. What if you need primitive arrays, such as int[], double[], and boolean [] instead?

One approach is to do the conversion yourself, like this.

The second approach is to use Java 8 Stream, like this.

Another approach to convert a List to a primitive array is by using Apache Commons Lang.

Converting List to Primitive Array with Apache Commons Lang

Apache Commons Lang provides extra methods for common functionalities and methods for manipulation of the core Java classes that is otherwise not available in the standard Java libraries.

To use Commons Lang, add the following dependency to your Maven POM.

Commons Lang comes with an ArrayUtils class meant specifically to perform operations on arrays. Out of the several methods that ArrayUtils provide, the methods of our interest are the overloaded toPrimitives() methods. Each of these overloaded methods accepts a wrapper array and returns the corresponding primitive array.

The code to convert a List to a primitive array using Commons Lang is this.

The test code is this.

Converting List to Primitive Array with Guava

Guava is a project developed and maintained by Google that comprise of several libraries extensively used by Java developer. To use Guava, add the following dependency to your Maven POM.

Guava contains several classes, such as Ints, Longs, Floats, Doubles, and Booleans with utility methods that are not already present in the standard Java wrapper classes. For example, the Ints class contains static utility methods pertaining to int primitives.

The Guava wrapper classes come with a toArray() method that returns a primitive array containing each value of the collection passed to it.

The code to convert a List to a primitive array using Guava is this.

The test code is this.

Converting Array to List

To convert an array to a List, you can use the Arrays.asList() method. This method returns a fixed-size list from the elements of the array passed to it.

An ArrayToListConverter class that converts an array to a List is this.

ArrayToListConverter.java

The JUnit test class is this.

ArrayToListConverterTest.java

Converting Array to List using Commons Collection

Commons Collection, similar to Commons Lang is part of the larger Apache Commons project. Commons Collection builds upon the Java collection framework by providing new interfaces, implementations, and utilities.

Before using the Commons Collection in your code, you need this dependency in your Maven POM.

CollectionUtils is one class in Commons Collection that provides utility methods and decorators for Collection instances. You can use the addAll() method of CollectionUtils to convert an array to a List. This method takes as parameters a Collection and an array. This method adds all the elements present in the array to the collection.

The code to convert an array to a List using the CollectionUtils class of Commons Collection is this.

The test code is this.

Converting Array to List using Guava

Guava comes with a Lists class with static utility methods to work with List objects. You can use the newArrayList() method of the Lists class to convert an array to a List. The newArrayList() method takes an array and returns an ArrayList initialized with the elements of the array.

The code to convert an array to a List using the Lists class of Guava is this.

The test code is this.

3
Share

In applications, you often need to work with a set of constant values. For example, representing a contract status with the “permanent”, “temp”, and “intern” values, or directions with the “north”, “south”, “east”, and “west” values.

In Java, you use the enum type (short for enumeration), a special datatype introduced in Java 5 to represent such list of predefined constants.

In this post I’ll discuss how to define and use enum types. I’ill also include example code along with JUnit test cases. If you are new to JUnit, I suggest going through my JUnit series of posts.

Defining Java Enums

You can define an enum type either independently outside of any class or as part of a class. The code to define an enum independently is this.

The preceding code defines an enum type, Days. The names of the enum type’s fields are in uppercase letters as they are constants.

Here is the JUnit test code.

The test code assigns a value to the day variable of the enum type, Days. The day variable can take any of the seven defined values. In this case it is set to SUNDAY. The test code then asserts the value.

The output on running the test in IntelliJ is this.

SImple Java Enum Test Output

You can also define an enum inside a class, like this.

SimpleEnumExample.java

Here is the JUnit test code.

The output on running the test in IntelliJ is this.

Java enum test output

Enums in if-else if Statements

Often you may require to compare a variable pointing to an enum constant against all the possible values in the enum. This can be done with if-else if statements.

The code to use enums in an if-else if statement is this.

EnumInIfStatement.java

Here is the JUnit test code.

The output on running the test in IntelliJ is this.
Test Output of Java Enum in If Statemnent

Enums in switch Statements

You can use enum in a switch statement. To do so, use the enum reference variable in the switch and enum constants or instances in case statements.

The code to use an enum type in a switch statement is this.

EnumInSwitchStatement.java

Here is the JUnit test code.

The output on running the test in IntelliJ is this.
Test Output of Java Enum in Switch Statement

Enum Iteration

You can iterate through an enum to access its values. The static values() method of the java.lang.Enum class that all enums inherit gives you an array of enum values.

Let us use the same enum type, Days defined in the SimpleEnumExample class and iterate through its values.

EnumIteration.java

The test code is this.

The output on running the test in IntelliJ is this.
Test Output Enum Iteration

Enum Fields and Methods

Java enums can have fields and methods. You can add fields against each enum constant and the enum gets initialized with the values. When defining the constants, the enum constructor must be supplied with the values.

Note: If a Java enum contains fields and methods, the definition of fields and methods must always come after the list of constants in the enum.

The code to define an enum with fields, constructor, and methods is this.

EnumFields.java

The AbbreviationOfDays enum has an abbreviation field of type String. The constructor takes a String abbreviation and assigns it to the field. The getAbbreviation() method returns the abbreviation field.

Note: You can also define methods that do some logical operations within an enum.

Here is the Junit test code.

The output on running the test in IntelliJ is this.
Test Output Java Enum Fields Methods

Key Points

Some key points on enum type are:

  • Java enum extends java.lang.Enum class implicitly. Therefore, you cannot extend any other class in enum.
  • Enums can implement interfaces. They implicitly implement the Serializable and Comparable interfaces. This means if you need some common functionality along diverse enum types you can define it with an interface to have the enums provide the method implementations.
  • In Java, enum is a keyword.
    Enum constructors are always private or default. Therefore, you cannot have public or protected constructors in an enum type.
  • In an enum definition, comma separated constants must be terminated with semicolon.
  • You cannot create an instance of enum using the new operator.
  • You can declare abstract methods within an enum. If you do so all the enum fields must implement the abstract methods.
  • You can use “==” operator to compare enum constants effectively, since enum constants are final.

Summary

I often see code with lots of int constants representing a set of predefined values instead of enums, which is a better fit. I attribute this to inexperience programmers who are not familar enums.

Enums remove “magic numbers”. These are numbers that don’t really mean anything on their own. By replacing those numbers with actual values, your code makes more sense and follows better coding principles.

Also, enums prevent incorrect values from being passed to a function. Consider that you have a method that takes an int value. This method will execute if we pass any int value. But if you want to restrict the values that the method takes as input, you should ideally use enums. This is what is called type safety. Enums lets you control the required set of inputs.

In enterprise application development with Spring, you will find enums defined in model classes. This is for applications that expects the users to provide the exact enums in the request which adds a validation for the incoming request.

0
Share

Converting a Java Map to a List is a very common task. Map and List are common data structures used in Java. A Map is a collection of key value pairs. While a  List is an ordered collection of objects in which duplicate values can be stored.

In this post, I will discuss different ways to convert a Map to a List.

For the example code in this post, I’ll provide JUnit tests. If you are new to JUnit, I suggest you go through my series on Unit Testing with JUnit.

Converting Map Keys to List

The Map class comes with the keyset() method that returns a Set view of the keys contained in the map. The code to convert all the keys of a Map to a Set is this.

Here is the JUnit test code.

The output on running the test in IntelliJ is this.
Test Output Java Map Key To List

Converting Map Values to List

You use the values() method of Map to convert all the values of Map entries into a List.

Here is the code to convert Map values to a List.

Here is the Junit test code.

The output on running the test in IntelliJ is this.
Test Output Map Values to List

Converting Map to List using Java 8 Streams

If you are into functional programming style, you can use streams introduced in Java 8, along with some utility classes like Collectors, which provides several useful methods to convert stream of Map entries to List.

The stream() method return a stream of the keys from the Set of the map keys that Map.keySet() returns. The collect() method of the Stream class is called to collect the results in a List.

The Collectors.toList() passed to the collect() method is a generalized approach. You can collect elements of Stream in specific collection, such as ArrayList, LinkedList, or any other List implementation. To do so, call the toColection() method, like this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.
Test Output Java Map Keys To List with Java 8 Streams

Converting Map values to List using streams is similar. You only need to get the stream of Map values that map.values() return, like this

The test code is this.

The test output in IntelliJ is this.
Test Output Map Values To List with Stream

Converting Generic Map to List using Stream and Java Lambdas

Till now I showed using method reference with stream to perform conversion of Map to List.
I personally prefer method reference over lambda expressions because I find them clear and concise.
Also, when using collection, you will typically use generic collections and perform conversions between them.

For such collections, you can use streams with lambda expressions, like this.

The code to use method reference is this.

Here is the JUnit test code.

The JUnit test output in IntelliJ is this.

0
Share

A common requirement while programming in Java is to convert String to int. UI inputs in Web-based HTML, JSP, or Thymeleaf templates are transferred to backend Java applications as strings. It is the application developer’s responsibility to perform any String to int conversions to fulfil business logic, such as calculating discounts, storing age, and so on.

In this post, I’ll discuss how to convert String in Java to int.

The Integer.parseInt Method

The Integer.parseInt() method takes as input a String and returns an int value.

The code to use this method is this.

Here is test code in JUnit.

The output on running the test in InteliJ is this.

Test Output converting string to int in Java

The Integer class also provides an overloaded parseInt() method that additionally accepts the radix (base) to be used while parsing.

Here is the code to use the overloaded method..

Here is the test code.

The output on running the test in InteliJ is this.
Java string to int using radix (base)

Handling Parsing Exception

The parseInt() method throws a NumberFormatException if the String does not contain a parsable int.

Here is sample code to handle the NumberFormatException  gracefully.

This code returns a default int value whenever a NumberFormatException is thrown by the parseInt() method.

Here is the Junit test code.

The test output is this.
Java string to int output

The Integer.valueOf Method

The Integer class also comes with the static valueOf() method to convert String to int. The valueOf() method interprets the String exactly as if it were given to parseInt(). In fact, the valueOf() method internally uses the parseInt() method.

However, valueOf() returns a new Integer object whereas parseInt() returns a primitive int.

The code to parse String using the valueOf() method is this.

Here is the Junit test code.

The test output is this.

Java string to integer output

Note: Similar to parseInt(), the valueOf() method also have an overloaded version that accepts an additional radix value.

Conclusion

Considering Java is a strongly typed language and often interfaces with systems that do not have the type system of Java, converting from a string value to an int value in Java is very common task. As you can see Java provides a number of different ways to convert a string value to an integer value.

 

0
Share

Java Architecture for XML Binding (JAXB) is a library that helps to bind XML schemas and Java representations. JAXB provides you with a mechanism to marshal Java objects into XML and the other way around – unmarshal XML into Java objects.

XML is an industry standard for defining the contents of your message. XML along with Java are complementary technologies to exchange data across the Internet. When you work with XML, you need a way to take an XML file, and then convert it into some sort of data structure, which your program can manipulate. You also need to serialize the state of your Java objects into XML. JAXB is one library that performs such marshalling and unmarshalling operations.

In this post, I will discuss on how to marshal Java objects into XML and the other way around using JAXB.

Using JAXB to Marshall Java Objects to XML

Let us consider a scenario where we need to model a product for an e-commerce store. Apart from fields, such as product Id, description, image URL, and price, a Product object is also composed of a User object that represents the user who adds the product to the store.

Our intent is to marshal the Product object, along with its composed User object into XML by using JAXB.

We can start by creating a User POJO to model the user.

User.java

User is a simple POJO with the id, name, and email fields, along with their corresponding getter and setter methods.

Next, we will create the Product POJO. While creating this POJO, we will use annotations introduced in JAXB 2.0 to control how our Product object is marshalled to XML.

Note: As from JDK 1.6, JAXB is bundled with JDK. Therefore you don’t need to add any dependency for it.

The code of the Product POJO is this.

Product.java

In this Product class, we used a number of JAXB annotations. They are:

  • @XmlRootElement: This annotation is used at the top level class to indicate the root element in the XML document. The name attribute in the annotation is optional. If not specified, the class name is used as the root XML element in the document.
  • @XmlAttribute: This annotation is used to indicate the attribute of the root element.
  • @XmlElement: This annotation is used on the properties of the class which will be the sub-elements of the root element.

The Product POJO is now ready to be marshalled into XML. To do so, let us write a JUnit test class. If you are new to JUnit, I suggest going through my Unit Testing with JUnit series.

The test class is this.

ProductToXmlTest.java

In this code:

  • Line 19 – Line 24: Instantiates and initializes a User and a Product object in the setup() method marked as @Before.
  • Line 33: The JAXBContext.newInstance() method obtains a JAXBContext for the Product class which you want to marshal. JAXBContext provides the entry point for the JAXB API.
  • Line 34: Creates a Marshaller through a call to the createMarshaller() method of JAXBContext. In JAXB, the Marshaller class governs the process of marshalling Java objects into XML data through its various marshalling methods.
  • Line 35: Configures the Marshaller. The true value of the JAXB_FORMATTED_OUTPUT property instructs the Marshaller to generate the XML with proper indentation.
  • Line 36: Calls the marshal() method on the Marshaller with the initialized Product object and the file to write the XML.
  • Line 37: Marshals the object to the “standard” output stream.

On running the ProductToXmlTest class, a product.xml file gets generated.

The output of the test is this.
JAXB Marshalling Test Output

Spring Framework 5
Become a Spring Framework Guru! Click here to learn more about my Spring Framework 5: Beginner to Guru online course!

Using JAXB to Unmarshall XML into Java Objects

Unmarshalling XML with JAXB to a Java object involves creating an Unmarshaller on the JAXBContext and calling the unmarshal() method. This method accepts the XML file to unmarshall.

The JUnit test class to unmarshall the generated product.xml back to the Product and User objects is this:

XmlToProductTest.java

In this XmlToProductTest class, a JAXBContext initialized with Product is used. The createUnmarsheller() method returns an Unmarshaller. A JAXB Unmarshaller governs the process of unmarhshalling XML data into a Java object tree. Finally, the unmarshal() method unmarshals the File object for product.xml into the Product POJO.

The output on running the test is this.
JAXB Unmarshalling Test Output

Handling Collections

Often you will need to marshall Java collection objects, such as List, Set, and Map to XML, and also unmarshall XML back to collection objects.

Consider our current application where we now need to work with a list of products. To model the new requirement, let us create a Products class.

The code of the Products class is this.

Products.java

In this Products class, the @XmlRootElement annotation specifies the root element of the XML as products. This class has a single List property with getter and setter methods. The add() method of this class accepts a Product object and adds it to the List.

The test class to convert a list of products to XML, is this.

ProductToXmlListTest.java

The output on running the test is this.

Summary

In this post, I have covered introductory concepts on JAXB. I have previously written a post on how to use an XML Schema and JAXB to generate Java classes for a RESTful Web services here.

JAXB also comes with a JAXB Binding compiler tool, named schemagen. You can use schemagen to generate an XSD schema from Java classes.

The source code for this post is available on github. You can download it here.

3
Share

One common requirement in Java application is to iterate through the elements of a collection. Prior to Java 8, the three most common ways to iterate through a collection are by using the while loop, for loop, and enhanced for loop. As the Java Collection interface extends Iterable, you can also use the hasNext() and next() methods of Iterable to iterate through collection elements.

Starting from Java 8, we have a new forEach method in Iterable to loop through elements in a collection – but in a different way.

In this post, I will discuss the  forEach method introduced in Java 8.

External vs Internal Iterators

Based on who controls iterations, Java Iterators can be classified into external and internal iterators.

External iterators are also known as active or explicit iterators. When using an external iterator, the client code performing the iteration controls the iteration. The client creates the iterator and instructs it when to advance to the next element. The client also checks whether or not all the element has been visited, and so on.

Enumerations, iterators, and enhanced for-loop are all examples of external iterators. Remember the old hasMoreElements() and nextElement() of Enumeration that you write to control iteration? Similarly, next() and hasNext() of Iterator?

The enhanced for loop introduced in Java 5 is another example of external iterator. An example of the enhanced for loop is this.

As evident from this code, the enhanced for loop shields developers from explicitly controlling looping via code. However, internally the next() and hasNext() methods get called, and therefor making it an external iterator.

Internal iterators are also known as passive, implicit or callback iterator. When you use an internal iterator, it is the iterator itself that controls the iteration. The client code essentially says to the iterator, “perform this operation on the elements in the collection.

Internal iterator has been introduced in Java 8 with the introduction of Lambda expression. The forEach method of this post covers is an internal iterator.

List Iteration using Java 8 forEach

The code to iterate through the elements of a list using forEach is this.

This code declaratively states what is meant to be done with the elements of the List. The internal iterator manages the iterations in the background.

To make the code clearer, the same iterateThroughList() method can be written using method reference like this.

You can test the code with this.

The output of the code in the IntelliJ console is this.
forEach List Iteration

Inside Java 8 forEach

In the example we just saw, we used lambda expressions. Let us dissect the forEach method and look what is happening inside.

The signature of the forEach method is this.

The forEach method performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. The Consumer parameter of forEach is a functional interface with the accept(Object) method.

We can therefore rewrite the previous iterateThroughList() method like this.

This code uses an anonymous class to instantiate a Consumer implementation. The Consumer instance is then passed as an argument to forEach. This code will produce the same result as the lambda expression we wrote.

Map Iteration using Java 8 forEach

Map in Java does not extends Iterable and therefore does not inherit Iterable’s forEach. However, Map itself has its own forEach method that you can use to iterate through key-value pairs.

The following code uses a lambda expression to do so.

You can test the code, with this.

The output of the code in the IntelliJ console is this.
forEach Map Iteration

Stream Iteration using Java 8 forEach

With both the new forEach method and the Java 8 Stream API, you can create a stream of elements in a collection and then pipeline the stream to a forEach method for iteration.

The code to iterate through a stream of elements in a List is this.

The code to test this method is this.

The output of the code is this.

For parallel streams, the only difference is that you need to call the parallelStream() method instead of stream() on the List. Then iterate through the stream of elements using forEach, like this.

The code to test this method is this.

The output of the code is this.
forEach Parallel Stream Iteration

As you can notice, the order in which the list elements are processed is not the order in which the elements are stored in the list. However, when dealing with larger sets of data, parallel streams bring in considerable performance gain to your program.

Conclusion

The new forEach method of Java 8 brings in a more declarative approach to iteration. As a developer, you write code to specify the result rather than how to compute it.

This new declarative approach is more readable but also less error prone.

In addition, the forEach() method fits intuitively with the Stream API and particularly makes using parallel streams easy.

3
Share

Prior to Jackson 1.2, the only way to serialize or deserialize JSON using Jackson was by using one of the following two methods:

  • Adding annotations to modify the POJO classes
  • Writing custom serializers and deserializers

Now imagine you want to serialize or deserialize a 3rd party POJO which you don’t have access to its source code. What would you do?

Also, you might want your code clean and open to other JSON library, such as GSON.

What would you do to decouple your code from Jackson annotations?

Jackson mix-in annotations helps you resolve this kind of problems. These annotations are used in a mix-in class or interface but function as if they were directly included in the target class.

In this post we will look at how to use the Jackson mix-in annotations.

Sample Application

Let us create a simple Spring Boot application to understand how Jackson mix-in annotation works.

Consider you want serialize or deserialize a User POJO in a Spring Boot application.

Here is code of the User POJO.

User.java

In the preceding code, User is a typical POJO but is not designed to be used with data binding. The User class doesn’t have the default constructor and neither any getter and setter methods.

Let’s assume that you don’t have access to the source code of the User POJO. Or there is some constraint disallowing you to modify the existing POJO. In this scenario, you can’t serialize or deserialize a User object through annotations or by defining your own custom serializer and deserializer.

Let us see how mix-in annotations can solve this problem.

The Jackson Mix-in Class

For mix-in annotation, you first need to define a mix-in class or interface.

Let’s define an abstract mix-in class for User. Ensure that the mix-in class have a constructor matching the source POJO.

Use the @JsonCreator annotation on the constructor and the @JsonProperty property to specify all the properties of the POJO.

Here is code for the UserMixin Jackson mix-in class.

UserMixin.java

UserMixin is an abstract class where the constructor of the class is annotated with @JsonCreator to tell Jackson in what order to pass fields from a JSON object to the constructor.

Each argument of the constructor is annotated with @JsonProperty to indicate the name of the property to bind to.

After creating the UserMixin class, you must configure the ObjectMapper to use the mix-in for the User POJO, like this.

Here is the complete test code to test the Jackson mix-in.

UserTest.java

As you can see in the code, ObjectMapper is configured in the buildMapper() method.

In the test method, an ObjectMapper is created and the addMixIn() method is called on it. The addMixIn() method configures the association between the mix-in and target classes, to be used during serialization.

Here is the output of the Jackson Mix-in test from IntelliJ:

Jackson Mixin Test Results

2
Share
, , ,

When developing Spring Boot applications, you need to tell the Spring Framework where to look for Spring components. Using component scan is one method of asking Spring to detect Spring managed components. Spring needs the information to locate and register all the Spring components with the application context when the application starts.

Spring can auto scan, detect, and instantiate components from pre-defined project packages. Spring can auto scan all classes annotated with the stereotype annotations @Component, @Controller, @Service, and @Repository

In this post, I will discuss how Spring component scanning works.

Sample Application

Let us create a simple Spring Boot application to understand how component scanning works in Spring.

We will start by writing few components.

DemoBeanA.java

DemoBeanB1.java

DemoBeanB2.java

DemoBeanB3.java

DemoBeanC.java

DemoBeanD.java

Spring Framework 5
Click Here to Become a Spring Framework Guru!

The @SpringBootApplication Annotation

Spring needs to know which packages to scan for annotated components in order to add them to the IoC container. In a Spring Boot project, we typically set the main application class with the @SpringBootApplication annotation. Under the hood, @SpringBootApplication is a composition of the @Configuration, @ComponentScan, and @EnableAutoConfiguration annotations. With this default setting, Spring Boot will auto scan for components in the current package (containing the @SpringBoot main class) and its sub packages.

To know more about these annotations go through my Spring Framework Annotations post.

Note: It is recommended that you locate your main application class in a root package above the component classes of the application.

The code to create the main class and access components is this.

BlogPostsApplication.java

The output of running the main class is this.
Output of BlogPostsApplication.java class

As you can notice, all the classes in the sub packages of the main class BlogPostsApplication are auto scanned by Spring.

@ComponentScan – Identifying Base Packages

The @ComponentScan annotation is used with the @Configuration annotation to tell Spring the packages to scan for annotated components. @ComponentScan also used to specify base packages and base package classes using thebasePackageClasses or basePackages attributes of @ComponentScan.

The basePackageClasses attribute is a type-safe alternative to basePackages. When you specify basePackageClasses, Spring will scan the package (and subpackages) of the classes you specify. 

A Java class annotated with @ComponentScan with the basePackageClassesattribute is this.

BlogPostsApplicationWithComponentScan.java

The output on running the main class is this.
Output of BlogPostsApplicationWithComponentScan.java Class

The @ComponentScan annotation uses the basePackages attribute to specify three packages (and subpackages) that will be scanned by Spring. The annotation also uses the basePackageClasses attribute to declare the DemoBeanB1 class whose package Spring Boot should scan.

As demoBeanC is in a different package, Spring did not find it during component scanning.

Component Scanning Filters

You can configure component scanning by using different type filters that Spring provides.

By using filters, you can further narrow the set of candidate components from everything in basePackages to everything in the base packages that matches the given filter or filters.

Filters can be of two types: include and exclude filters. As their names suggest, include filters specify which types are eligible for component scanning, while exclude filters specify which types are not.

You can use the include and/or exclude filters with or without the default filter. To disable the default filter, set the useDefaultFilters element of the @ComponentScan annotation to false.

The code to disable the default filter is this.

BlogPostsApplicationDisablingDefaultFilters.java

In the preceding code, the value member defines the specific guru.springframework.blog.componentscan.example.demopackageA package to scan, while the useDefaultFilters member disables the default filter.

The output on running the main class is this.
Output of BlogPostsApplicationDisablingDefaultFilters.java Class

As you can notice, the class DemoBeanA in the package demopackageA is unavailable when the useDefaultFilters element of the @ComponentScan annotation is set to false.

Component Scanning Filter Types

Spring provides the FilterType enumeration for the type filters that may be used in conjunction with @ComponentScan.

The available FilterType values are:

  • FilterType.ANNOTATION: Include or exclude those classes with a stereotype annotation
  • FilterType.ASPECTJ: Include or exclude classes using an AspectJ type pattern expression
  • FilterType.ASSIGNABLE_TYPE: Include or exclude classes that extend or implement this class or interface
  • FilterType.REGEX: Include or exclude classes using a regular expression
  • FilterType.CUSTOM: Include or exclude classes using a custom implementation of the org.springframework.core.type.TypeFilter interface

Include Filters

With include filters, you can include certain classes to be scanned by Spring. To include assignable type, use the includeFilters element of the @ComponentScan annotation with FilterType. ASSIGNABLE_TYPE. Using this filter, you can instruct Spring to scan for classes that extends or implements the class or interface you specify.

The code to use the includeFilters element of @ComponentScan is this.

BlogPostsApplicationIncludeFilter.java