Spring Autowiring Tips
How to support null properties, clean up component scan and nullable beans
First, off when building out a Spring boot app you need to get your beans to load. In order to do this you need to setup a component scan. Sometimes @Service objects don’t resolve properly, so you need to update the filters in the component scan. Also, the root of the application package is typically the default package unless you override the specific details. Overriding the component scan will allow you to change package scans for the given application.
For example:
package com.package
import org.springframework.boot.autoconfigure.SpringBootApplication
import org.springframework.boot.SpringApplication;
import org.springframework.context.annotation.ComponentScan
import org.springframework.context.annotation.ComponentScan.Filter
@SpringBootApplication
@ComponentScan(basePackages = {"com.package"}, excludeFilters = {
@Filter(type = FilterType.CUSTOM, classes = TypeExcludeFilter.class),
@Filter(type = FilterType.CUSTOM, classes = AutoConfigurationExcludeFilter.class) })
public class MyApplication {
public static void main(String[] args) {
SpringApplication.run(MyApplication.class, args);
}
}The above example removes filters from the default Filter configuration of component scan allowing for some objects to be found that wouldn’t of been found before. This can increase startup time, keep in mind component scan in spring is one of the biggest performance issues with startup time of an application.
Application Properties
When you have some optional application.properties values, you need to specify in your configuration object that the value is nullable by setting a default value. If you don’t know how to set a default value, it’s easy, set the value on the opposite side of a : in the property reference.
There are 2 ways of setting null on a property in the Spring annotation.
Option 1: Use #{null}
@Configuration
public class MyConfiguration {
@Value("${optional.property.value:#{null}}")
String optionalValue;
}Option 2: Empty :
@Configuration
public class MyConfiguration {
@Value("${optional.property.value:}")
String optionalValue;
}Nullable Autowired Beans
If you have optional beans that you are autowiring into your class, you need to make sure they can be null. This is a good technique for an optional plugin model where depending on if the class is loaded into the context or not you do some conditional logic on it.
Example:
@Component
public MySpringBean {
@Autowired(required=false)
private MyBean myBean;
}References
Other references to follow up on: