junit @resource 没有注入_Java程序员自动组件注入的几种方式你会哪一种?

cb7bb776be748641ebb52e7617f654b6.png

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

1bc2036444d8cc88e69bd916c56f8186.png

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();

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
JUnit 测试类无法完成资源注入某个类的原因可能有几种。以下是一些常见的可能原因和解决方法: 1. JUnit 测试类没有使用 Spring 的测试注解:如果你希望在 JUnit 测试类完成资源注入,你需要使用 Spring 提供的测试注解,例如 `@RunWith(SpringRunner.class)` 或 `@ExtendWith(SpringExtension.class)`。这些注解启用 Spring 的测试上下文,并允许资源注入。确保你正确地使用了这些注解。 2. 测试类没有配置正确的上下文:如果你使用了 Spring 的注解进行资源注入,确保你的测试类所在的包已经包含在 Spring 上下文的扫描范围内。你可以通过在测试类上添加 `@ComponentScan` 或 `@SpringBootTest` 等注解来配置正确的上下文。 3. 资源注入的类没有被正确定义为 Spring Bean:确保你希望注入的类已经被正确地定义为 Spring Bean。你可以在该类上添加 `@Component`、`@Service`、`@Repository` 或其他合适的注解来将其标记为 Spring Bean。 4. 依赖注入框架未正确配置:如果你使用了其他依赖注入框架(如 Guice),确保你已经正确地配置了框架,并且在测试类使用了正确的注解来进行资源注入。 5. 测试类没有使用适当的注入方式:在测试类进行资源注入时,你可以使用 `@Autowired`、`@Inject` 或 `@Resource` 等注解来标记要注入的资源。确保你使用了适合的注解,并将其应用到正确的位置。 请根据你的具体情况检查以上可能的原因,并尝试相应的解决方法。如果问题仍然存在,请提供更多的代码和错误信息,以便我能够更具体地帮助你解决问题。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值