Spring @Resource注释
除了使用@Autowired批注之外,在Spring中进行自动装配还支持JSR 330的@Inject批注和JSR-250 @Resource批注。在本文中,我们将介绍如何使用Spring @Resource批注进行自动装配。
Spring中的@Resource注释
@Resource批注可用于字段或者bean属性设置器方法。 @Resource具有名称属性。默认情况下,Spring将该值解释为要注入的Bean名称。换句话说,此注释遵循autowire = by-name语义。
例如
@Service
public class OrderService {
private IStore store;
// Autowired on Setter
@Resource(name="retailStoreBean")
public void setStore(IStore store) {
this.store = store;
}
public void buyItems() {
store.doPurchase();
}
}
Spring将在存储属性中寻找一个名为" retailStoreBean"的bean注入此处。
用@Resource批注指定的名称是可选的。如果未明确指定名称,则默认名称是从字段名称或者setter方法派生的。
如果是字段,则使用字段名称。在使用setter方法的情况下,它采用bean属性名称。
如果@Resource注释找不到同名的bean,它将尝试使用type进行匹配。因此,如果不满足按名称自动装配的要求,还可以自动切换到autowire = byType。
Spring @Resource注释示例
在该示例中,有一个用于下订单的类称为OrderService,可以从商店进行购买。在OrderService类中,必须自动关联商店的依赖关系,并为其使用@Resource批注。
javax.annotation.Resource是javax.annotation API的一部分,因此我们可能需要添加该依赖项才能使用@Resource批注。
<dependency>
<groupId>javax.annotation</groupId>
<artifactId>javax.annotation-api</artifactId>
<version>1.3.2</version>
</dependency>
OrderService.java
import javax.annotation.Resource;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private IStore store;
// Autowired on Setter
@Resource(name="retailStoreBean")
public void setStore(IStore store) {
this.store = store;
}
public void buyItems() {
store.doPurchase();
}
}
这里name属性的值是" retailStoreBean",这意味着应该有一个必须将此名字注入到store属性中的bean。
istore界面
public interface IStore {
public void doPurchase();
}
RetailStore.java
@Component("retailStoreBean")
public class RetailStore implements IStore {
public void doPurchase() {
System.out.println("Doing purchase from Retail Store");
}
}
Bean的名称为" retailStoreBean",这是此Bean在容器中注册的名称。
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" />
</beans>
类运行示例
public class App {
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("appcontext.xml");
OrderService orderService = context.getBean("orderService", OrderService.class);
orderService.buyItems();
}
}
输出:
Doing purchase from Retail Store
如果名称被删除,则代码直到@Resource都将切换为byType自动装配。
@Resource
public void setStore(IStore store) {
this.store = store;
}

