Spring Boot 使用@Resource (JSR250)和@Inject (JSR330)实现依赖注入

Spring框架还兼容JSR标准,我们能使用@Resource或@Inject注解实现依赖注解的功能,不过他们与@Autowired有细微的差别。

  • 使用@Resource注解。@Resource注解必须要设置name属性(需要注入Bean的ID),且无法配合@Primary注解使用和不支持设置required属性功能。
import com.michael.annotation.demo.POJO.Student;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

@Service
public class StudentService {

    @Resource(name = "s2")
    public Student student;

    public void  showInfo(){
        System.out.println(student);
    }
}
  • 在使用@Inject注解之前,我们需要在pom文件中加入支持JSR330依赖;该注功能几乎和@Autowired一样(可配合@Qualifier或@Primary使用),但是不支持设置required属性值(当值为false,在容器中找不到所需的Bean时,返回null)。
		<dependency>
            <groupId>javax.inject</groupId>
            <artifactId>javax.inject</artifactId>
            <version>1</version>
        </dependency>
import com.michael.annotation.demo.POJO.Student;
import org.springframework.stereotype.Service;

import javax.inject.Inject;

@Service
public class StudentService {

    @Inject
    public Student student;

    public void  showInfo(){
        System.out.println(student);
    }
}
发布了70 篇原创文章 · 获赞 4 · 访问量 3020

猜你喜欢

转载自blog.csdn.net/qq_34515959/article/details/105132679
今日推荐