标题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("啓動");
}
}