@Autowired、@Resource和@Inject注解的区别(最详细)
共 11130字,需浏览 23分钟
·
2021-01-06 15:05
点击上方蓝色字体,选择“标星公众号”
优质文章,第一时间送达
@Target({ElementType.CONSTRUCTOR, ElementType.METHOD,
ElementType.PARAMETER, ElementType.FIELD, ElementType.ANNOTATION_TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Autowired {
boolean required() default true;
}
{@link org.springframework.beans.factory.config.BeanPostProcessor BeanPostProcessor}
* implementation that autowires annotated fields, setter methods, and arbitrary
* config methods. Such members to be injected are detected through annotations:
* by default, Spring's {@link Autowired @Autowired} and {@link Value @Value}
* annotations.
*
* Also supports JSR-330'
s {@link javax.inject.Inject @Inject} annotation,
* if available, as a direct alternative to Spring's own {@code @Autowired}.
@Target({TYPE, FIELD, METHOD})
@Retention(RUNTIME)
public @interface Resource {
String name() default "";
String lookup() default "";
Class> type() default java.lang.Object.class;
enum AuthenticationType {
CONTAINER,
APPLICATION
}
AuthenticationType authenticationType() default AuthenticationType.CONTAINER;
boolean shareable() default true;
String mappedName() default "";
String description() default "";
}
* {@link org.springframework.beans.factory.config.BeanPostProcessor} implementation
* that supports common Java annotations out of the box, in particular the JSR-250
* annotations in the {@code javax.annotation} package. These common Java
* annotations are supported in many Java EE 5 technologies (e.g. JSF 1.2),
* as well as in Java 6's JAX-WS.
*
* This post-processor includes support for the {@link javax.annotation.PostConstruct}
* and {@link javax.annotation.PreDestroy} annotations - as init annotation
* and destroy annotation, respectively - through inheriting from
* {@link InitDestroyAnnotationBeanPostProcessor} with pre-configured annotation types.
*
*
The central element is the {@link javax.annotation.Resource} annotation
* for annotation-driven injection of named beans, by default from the containing
* Spring BeanFactory, with only {@code mappedName} references resolved in JNDI.
* The {@link #setAlwaysUseJndiLookup "alwaysUseJndiLookup" flag} enforces JNDI lookups
* equivalent to standard Java EE 5 resource injection for {@code name} references
* and default names as well. The target beans can be simple POJOs, with no special
* requirements other than the type having to match.
@Component
public class Student {
private String num = "1";
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
@Configuration
@ComponentScan(basePackages = {"it.cast.autowired"})
public class Config {
@Bean
public Student student1(){
Student student = new Student();
student.setNum("2");
return student;
}
}
@Component
public class Teacher {
@Resource //注意这里使用的@Resource注解,Spring支持注入Map、Conllent类型的属性变量
private Mapstudent;
public MapgetStudent() {
return student;
}
public void setStudent(Mapstudent) {
this.student = student;
}
}
public class Test01 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Teacher teacher = context.getBean(Teacher.class);
System.out.println(teacher.getStudent());
}
}
//打印结果:
//Caused by: org.springframework.beans.factory.BeanNotOfRequiredTypeException: Bean named 'student' is expected to be of type 'java.util.Map' but was actually of type 'it.cast.autowired.Student'
// at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:392)
// at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:204)
// at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeanByName(AbstractAutowireCapableBeanFactory.java:452)
// at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.autowireResource(CommonAnnotationBeanPostProcessor.java:527)
// at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.getResource(CommonAnnotationBeanPostProcessor.java:497)
// at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor$ResourceElement.getResourceToInject(CommonAnnotationBeanPostProcessor.java:637)
// at org.springframework.beans.factory.annotation.InjectionMetadata$InjectedElement.inject(InjectionMetadata.java:180)
// at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:90)
// at org.springframework.context.annotation.CommonAnnotationBeanPostProcessor.postProcessProperties(CommonAnnotationBeanPostProcessor.java:322)
// ... 12 more
@Component
public class Student {
private String num = "1";
public String getNum() {
return num;
}
public void setNum(String num) {
this.num = num;
}
}
@Configuration
@ComponentScan(basePackages = {"it.cast.autowired"})
public class Config {
@Bean
public Student student1(){
Student student = new Student();
student.setNum("2");
return student;
}
}
@Component
public class Teacher {
@Autowired //注意这里使用的@Autowired注解,Spring支持注入Map、Conllent类型的属性变量
private Mapstudent;
public MapgetStudent() {
return student;
}
public void setStudent(Mapstudent) {
this.student = student;
}
}
public class Test01 {
public static void main(String[] args) {
AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(Config.class);
Teacher teacher = context.getBean(Teacher.class);
System.out.println(teacher.getStudent());
}
}
//其打印结果:
//{student=it.cast.autowired.Student@61009542, student1=it.cast.autowired.Student@77e9807f}
@Configuration
@ComponentScan({"it.cast.resouce"})
public class ResourceConfig {
@Primary //标有Primary注解,使用@Autowired@Inject注解注解时,优先被加载
@Bean
public Y y1(){
Y y = new Y();
y.setI(0);
return y;
}
}
@Component
public class X {
@Resource //这里使用的是@Resource注解,该注解默认按照组件名称进行装配的,所以会优先加载id为y的bean
private Y y;
public Y getY() {
return y;
}
public void setY(Y y) {
this.y = y;
}
}
@Component
public class Y {
private int i = 2;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
@Test
public void ResourceConfigTest(){
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ResourceConfig.class);
X bean = context.getBean(X.class);
System.out.println(bean.getY().getI());
}
//输出结果为:
// 2
//从而验证了@Resource默认按照名称进行加载
@Configuration
@ComponentScan({"it.cast.resouce"})
public class ResourceConfig {
@Primary //标有Primary注解,使用@Autowired@Inject注解注解时,优先被加载
@Bean
public Y y1(){
Y y = new Y();
y.setI(0);
return y;
}
}
@Component
public class X {
@Resource //这里使用的是@Resource注解,该注解默认按照组件名称进行装配的,所以会优先加载id为y12的bean,
private Y y12; //如果找不到则按Primary注解标注的bean进行注入
public Y getY() {
return y12;
}
public void setY(Y y) {
this.y12 = y;
}
}
@Component
public class Y {
private int i = 2;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
@Test
public void ResourceConfigTest(){
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ResourceConfig.class);
X bean = context.getBean(X.class);
System.out.println(bean.getY().getI());
}
//输出结果为:
// 0
//由于没有找到id为y12的bean,所以注入了使用@Primary标注的bean,
//而且整个程序没有报错,所以验证了@Resource支持@Primary注解
@Configuration
@ComponentScan({"it.cast.resouce"})
public class ResourceConfig {
@Primary //标有Primary注解,使用@Autowired@Inject注解注解时,优先被加载
@Bean
public Y y1(){
Y y = new Y();
y.setI(0);
return y;
}
}
@Component
public class X {
@Autowired
private Y y; //此时不管名称是y还是y12,都会使用标有Primary注解的bean
public Y getY() {
return y;
}
public void setY(Y y) {
this.y = y;
}
}
@Component
public class Y {
private int i = 2;
public int getI() {
return i;
}
public void setI(int i) {
this.i = i;
}
}
@Test
public void ResourceConfigTest(){
AnnotationConfigApplicationContext context =
new AnnotationConfigApplicationContext(ResourceConfig.class);
X bean = context.getBean(X.class);
System.out.println(bean.getY().getI());
}
//输出结果为:
// 0
//从而验证了@Autowired支持@Primary注解
@Target({ METHOD, CONSTRUCTOR, FIELD })
@Retention(RUNTIME)
@Documented
public @interface Inject {} //该注解中没有任何属性
版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:
https://blog.csdn.net/qq_35634181/article/details/104276056
粉丝福利:Java从入门到入土学习路线图
???
?长按上方微信二维码 2 秒
感谢点赞支持下哈