The Spring framework enables automatic dependency injection. In other words, by
declaring
all the bean dependencies in a Spring configuration file, Spring container canautowire
relationships between collaborating beans. This is calledSpring bean autowiring
.
@Autowired 的使用是有前置条件的 ☞ activate the dependency injection annotations
To use Java-based configuration
in our application, let’s enable annotation-driven injection
to load our Spring configuration:
@Configuration
@ComponentScan("com.autowire.sample")
public class AppConfig {}
The
annotation is mainly used to activate the dependency injection annotations
in Spring XML files.
Spring Boot introduces the @SpringBootApplication
annotation. This single annotation is equivalent to using @Configuration
, @EnableAutoConfiguration
, and @ComponentScan
.
As a result, when we run this Spring Boot application, it will automatically scan
the componentsin the current package and its sub-packages. Thus it will register
them in Spring’s Application Context, and allow us to inject
beans using @Autowired.
阅读更多:
Spring <context:annotation-config> and <context:component-scan>
Spring Component Scanning
Spring @ComponentScan – Filter Types
There are four modes of autowiring a bean using an XML configuration
1、 no: the default value – this means no autowiring is used for the bean and we have to explicitly name the dependencies
.
2、 byName: autowiring is done based on the name of the property
, therefore Spring will look for a bean with the same name as the property that needs to be set.
3、 byType: similar to the byName autowiring, only based on the type of the property
. This means Spring will look for a bean with the same type of the property to set. If there’s more than one
bean of that type, the framework throws an exception
.
3、constructor: autowiring is done based on constructor arguments, meaning Spring will look for beans with the same type as the constructor arguments
.
@Bean(autowire = Autowire.BY_TYPE)
public class Store {
private Item item;
public setItem(Item item){
this.item = item;
}
}
public class Store {
@Autowired
private Item item;
}
<bean id="store" class="org.store.Store" autowire="byType"> </bean>
# more than one bean of the same type,use the @Qualifier to reference a bean by name
public class Store {
@Autowired
@Qualifier("item1")
private Item item;
}
<bean id="item" class="org.store.ItemImpl1" />
<bean id="store" class="org.store.Store" autowire="byName"> </bean>
We can also override the autowiring by defining dependencies explicitly through constructor arguments
or setters
.
参考:Intro to Inversion of Control and Dependency Injection with Spring