Skip to main content

Fun Annotation Notes

@ComponentScan + @Component

During Spring initialization the class that is marked with @ComponentScan will have it's package and it's subpackage scanned for any class that's marked with @Component. If any @Component class is found then it will add them to the application context (Basically contains the beans that will be managed by Spring).

Spring resolves dependencies between Spring beans and injects beans into each other's fields or constructor in order to satisfy the dependency.

@Autowired / @Inject

@Autowired and @Inject can be used interchangeably. Spring created @Autowired, @Inject is part of Java but Spring supports it fully.

This is the annotation that is used to actually inject the dependency into the class. There are many styles of doing the injection, you can do:

  • Field injection: Putting @Autowired on the private field of the class will inject that field for you
  • Setter injection: Putting @Autowired on the setter for that particular field that you are injecting of the class
  • Constructor injection: Putting @Autowired on the class's constructor for dependency injection

For Spring 4.3+, if a class that is configured as a Spring bean or component, only have one constructor and constructor have the wanted auto injected field in the parameter, then you can skip out on the @Autowired annotation.

Before Spring 4.3:

@Component
public class ExampleDB {
	
	private ExampleRecord record;
    
    @Autowired
    public ExampleDB(ExampleRecord record) {
    	this.record = record;
    } 
}

After:

@Component
public class ExampleDB {
	
	private ExampleRecord record;
    
    public ExampleDB(ExampleRecord record) {
    	this.record = record;
    } 
}

As you can see this is more leegant, BUT, at the cost of context. If you don't specify it explicitly the programmer will not know at immediately that record is an injected dependency.