[Spring] annotation-driven development - automatic assembly - @ Resource & @ Inject

This blog demo source address
https://github.com/suchahaerkang/spring-annotation.git

Part blog we learned through automatic annotation @Autowired spring assembly provided. This blog will introduce two notes java provides for automatic assembly
JSR250 提供的@Resource和JSR330提供@Inject,JSR250和JSR330都是java规范

1 @Resource

Here I am again on the modified code base blog on the previous article, we are registered BookService and BookDao components and BookService rely BookDao components. We deliberately registered registered two component types are BookDao example, in the container id are bookDao and bookDao2, and when the registration bookDao2 @Primary added annotation, its priority is to make automated assembly. Look unclear last article , where I will not put all the code stickers out. Now we will automatically inject BookService annotation notes @Autowired commented, replaced @Resource

/**
 * @description:
 * @author: sukang
 * @date: 2020-03-04 15:09
 */
@ToString
@Service
public class BookService {

    @Qualifier("bookDao2")
    //@Autowired(required = false)
    @Resource
    private BookDao bookDao;
}

operation result
Here Insert Picture Description
从结果看出,虽然我们通过@Primary设置了bookDao2优先注入的权力和@Qualifier指定bookDao2优先注入,但是最后注入的是bookDao,所以我们得出结论是java提供的@Resource注解默认是按照注入的属性名去容器中找相应的实例的, 不能和spring提供的@Qualifier和@Primary配合使用,并且不能像@Autowired注解一样使用required = false

2 @Inject

Using this annotation is necessary to introduce a java dependencies
Here Insert Picture Description
after dependencies lead to project into the annotation @Resource @Inject Autowiring

/**
 * @description:
 * @author: sukang
 * @date: 2020-03-04 15:09
 */
@ToString
@Service
public class BookService {

    @Qualifier("bookDao2")
    //@Autowired(required = false)
    //@Resource
    @Inject
    private BookDao bookDao;
}

operation result
Here Insert Picture Description
从结果我们可以看出@Primary起作用了,说明@Inject和@Autowired注解的功能差不多,只是@Inject没有@Autowired的required = false功能

3 summary

@Autowired,@Inject和@Resource都可以进行自动装配,只是前面一个是spring提供的,后面两个是java提供。如果项目中用到了spring这个框架,最好是用@Autowired,因为@Autowired相对而言功能多一点。

4 additional relevant knowledge @Autowired

@Autowired only be marked on the properties, but also marked in the constructor, and a method of the above parameters
Here Insert Picture Description
1)如果标注在方法上面,那么组件在创建,初始化时候回调用这个方法,并且方法所带的参数都可以直接去容器中去找,不需要要标注任何注解
2)如果标注在有参构造函数上面,那么组件在创建的时候是通过有参构造函数来创建的,并且有参构造函数需要的参数都可以直接去容器中获取。另外如果一个组件中只有一个有参构造函数,没有无参构造函数,那么可以省略标注@Autowired这个注解,实现的效果是一样的
PS:如果配置类中通过@Bean标注在有参函数进行注册组件的话,这个有参函数想要的参数组件也可以省略@Autowired注解,直接去容器中获取

Published 78 original articles · won praise 32 · views 90000 +

Guess you like

Origin blog.csdn.net/suchahaerkang/article/details/104716605