@Resoure注解

Last updated: ... / Reads: 46 Edit

@Resource 是Java EE 提供的注解之一,用于进行依赖注入。在Spring框架中,它也可以被使用,但通常不如 @Autowired 灵活。@Resource 可以标注在字段、Setter方法、构造函数上,用于指定需要注入的bean。

以下是 @Resource 的一些用法示例:

  1. 字段注入:
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    @Resource
    private MyRepository myRepository;

    // rest of the class
}

@Autowired 不同,@Resource 注解默认按照名称(byName)进行自动装配。如果没有指定 name 属性,则默认使用字段名或方法名(去掉首字母的大小写)作为bean的名称。

  1. Setter方法注入:
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private MyRepository myRepository;

    @Resource
    public void setMyRepository(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // rest of the class
}
  1. 构造函数注入:
import javax.annotation.Resource;
import org.springframework.stereotype.Service;

@Service
public class MyService {

    private final MyRepository myRepository;

    @Resource
    public MyService(MyRepository myRepository) {
        this.myRepository = myRepository;
    }

    // rest of the class
}

@Autowired 注解不同的是,@Resource 没有提供按照类型进行自动装配的选项。它主要通过 name 属性指定bean的名称进行注入。

需要注意的是,@Resource 是Java EE 的标准注解,因此在非Java EE环境下可能需要额外的配置才能生效。在Spring应用中,通常更常用和推荐使用 @Autowired 注解。


Comments

Make a comment