springboot构造注入方法

本文详细介绍了如何在Spring Boot中使用构造注入,包括私有化对象、@Autowired注解的使用、@Qualifier选择实现类,通过示例代码演示了整个过程。适合初学者理解Spring Boot依赖注入机制。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

标题springboot构造注入方法

构造注入相对麻烦一点
,首先和对象注入的区别是需要将一个新的类和已有实现类进行关联,
1:先私有化对象(不用@Autowired 修饰)

2:@Autowired修饰构造方法,参数于对象名一致,存在多个实现类时,使用@Qualifier在参数位置进行选择,
参考代码如下

package com.cy.pj.common.service;
importorg.springframework.beans.factory.annotation.Autowired;
importorg.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.cy.pj.common.cache.Cache;

@Component
public class SerachService {
private Cache cache;
@Autowired
public SerachService(@Qualifier(“weakCache”)Cache cache) {
this.cache=cache;
System.out.println(cache);
}
}

package com.cy.pj.common.service;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

@SpringBootTest
public class SerachServiceTests {
	@Autowired
	  private SerachService searchService;
	  @Test
	  void testSearchService() {
		  System.out.println(searchService);
		  System.out.println("啓動");
	  }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值