Spring @Autowired注释
时间:2020-01-09 10:44:29 来源:igfitidea点击:
Spring @Autowired注释用于自动注入依赖项。
在哪里应用@Autowired注释
- 我们可以将@Autowired注释应用到setter方法。参见示例。
- 我们可以将@Autowired注释应用于构造函数。参见示例。
- 我们可以将@Autowired应用于字段。参见示例。
- 我们还可以将注释应用于具有任意名称和多个参数的方法。参见示例。
启用@Autowired注释
要使用@Autowired注释启用自动装配,必须注册" AutowiredAnnotationBeanPostProcessor"类。我们可以直接为其提供bean定义,尽管很少需要。
<bean class = "org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor" />
通过使用<context:annotation-config>元素或者使用<context:component-scan>元素(隐式启用<context:annotation-config>元素的功能),将自动注册AutowiredAnnotationBeanPostProcessor类。这是启用它的首选方法。
Spring @Autowired注释示例
在该示例中,有一个用于下订单的类称为OrderService,可以从商店进行购买。在OrderService类中,必须自动关联商店的依赖关系。使用这些类,我们将了解如何将@Autowired与构造函数,setter,字段或者任意方法结合使用。
在setter上使用@Autowired注释
如果将@Autowired注释应用到setter方法上,就XML配置而言,它等效于autowiring =" byType"。
public interface IStore {
public void doPurchase();
}
import org.springframework.stereotype.Service;
@Service
public class RetailStore implements IStore {
public void doPurchase() {
System.out.println("Doing purchase from Retail Store");
}
}
public interface OrderService {
public void buyItems();
}
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class OrderServiceImpl implements OrderService {
private IStore store;
// Autowired on Setter
@Autowired
public void setStore(IStore store) {
this.store = store;
}
public void buyItems() {
store.doPurchase();
}
}
在这里,我们可以看到通过使用setStore()方法上的@Autowired注释可以满足对Store的依赖。
XML配置
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.theitroad.springproject.service" />
</beans>
在构造函数上使用@Autowired注释
在进行XML配置的情况下,bean的构造函数上的@Autowired注释等效于autowiring =" constructor"。
@Service
public class OrderServiceImpl implements OrderService {
private IStore store;
// Autowired on constructor
@Autowired
public OrderServiceImpl(IStore store){
this.store = store;
}
public void buyItems() {
store.doPurchase();
}
}
在字段上使用@Autowired注释
使用配置文件进行自动装配时,@ Autowired字段上的注释等效于autowiring =" byType"。
@Service
public class OrderServiceImpl implements OrderService {
// Autowiring on a field
@Autowired
private IStore store;
public void buyItems() {
store.doPurchase();
}
}
在任意方法上使用@Autowired注释
我们还可以将注释应用于具有任意名称和多个参数的方法。这些参数中的每一个都将与Spring容器中的匹配bean自动连接。
@Service
public class OrderServiceImpl implements OrderService {
private IStore store;
// Autowiring on a method
@Autowired
public void prepare(IStore store) {
this.store = store;
}
public void buyItems() {
store.doPurchase();
}
}

