首页 > 编程语言 > 详细

Java程序员自动组件注入的几种方式你会哪一种?

时间:2020-02-29 00:03:35      阅读:59      评论:0      收藏:0      [点我收藏+]
Java程序员自动组件注入的几种方式你会哪一种?

技术分享图片
Java程序员在开发的时候,一般都会遇到组件注入这个问题,回想起当年刚进入Java程序员这个行业的时候也遇到过这样的问题,那么我们今天就来讨论一下组件注入会有哪几种方式,希望能帮助大家快速攻破这个技术难点。

注入依赖对象可以采用手工装配或自动装配,在实际应用中建议使用手工装配,因为自动装配会产生未知情况,开发人员无法预见最终的装配结果。

问题1:@Autowired 、@Inject 、@Resource 的区别

@Autowired

[if !supportLists]· [endif]Spring标准

[if !supportLists]· [endif]按照类型注入(ByType)

[if !supportLists]· [endif]AutowiredAnnotationBeanPostProcessor对其进行处理

[if !supportLists]· [endif]支持属性、set方法、构造方法注入,可以联合@Qualifier完成ByName,联合@Primary解决同类多 Bean冲突(不推荐,除非迫不得已)

[if !supportLists]· [endif]拥有required属性判定空

[if !supportLists]· [endif]构造函数只能有一个,构造方法注入@Autowire可以不带

[if !supportLists]· [endif]@Configuration中也可以不带@Autowire

[if !supportLists]· [endif]推荐set方法、构造方法注入

@Resource

[if !supportLists]· [endif]JSR250标准

[if !supportLists]· [endif]按照名称注入(ByName)

[if !supportLists]· [endif]CommonAnnotationBeanPostProcessor对其进行处理

[if !supportLists]· [endif]不支持@Qualifier、@Primary

[if !supportLists]· [endif]不支持required属性判定空

@Inject

[if !supportLists]· [endif]JSR330

[if !supportLists]· [endif]按照名称注入(ByType)

[if !supportLists]· [endif]支持@Qualifier、@Primary

[if !supportLists]· [endif]不支持required属性判定空

[if !supportLists]· [endif]需要依赖

<dependency>

    <groupId>javax.inject</groupId>

    <artifactId>javax.inject</artifactId>

    <version>1</version>

</dependency>

问题2:下面代码有没有问题?

@Configuration

public class WorkerConfiguration {

@Autowired

Environment environment;

public WorkerConfiguration(){

    System.out.println(environment.getProperty("os.name"));

}

@Bean

public Dept dept() {

    System.out.println("dept>>>>>>>>>>>>>>>>>>>");

    return new Dept();

}

}

Java程序员自动组件注入的几种方式你会哪一种?

原文:https://blog.51cto.com/14698881/2474327

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!