我正在尝试获取 NoUniqueBeanDefinitionException 但我没有得到任何线索为什么我没有得到
package com.example.demo;
public interface IDateGen {
}
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class DateGen implements IDateGen {
}
package com.example.demo;
import org.springframework.stereotype.Service;
@Service
public class DateGen2 implements IDateGen {
}
package com.example.demo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
@Component
public class DateGenUtil {
@Autowired
private IDateGen dateGen;
public IDateGen getDateGen() {
return dateGen;
}
public void setDateGen(IDateGen dateGen) {
this.dateGen = dateGen;
}
}
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
@SpringBootApplication
public class Demo3Application {
public static void main(String[] args) {
ApplicationContext appContext = SpringApplication.run(Demo3Application.class, args);
DateGenUtil util = appContext.getBean(DateGenUtil.class);
System.out.println(util.getDateGen());
}
}
当我运行 main 方法时,我得到了
com.example.demo.DateGen@6075b2d3
谁能告诉我为什么我没有收到 NoUniqueBeanDefinitionException ?提前致谢
答案 0 :(得分:0)
依赖注入首先按类型检查自动装配,然后按名称自动装配,然后在类 DateGenUtil 中查找 dateGen 依赖项,然后按类型检查,然后获取两个对象,然后再次尝试执行 autoWiringByName 它获取一个对象
如果我们像下面的代码一样重命名变量,它会给出异常,希望任何人都可以确认这一点
@Component
public class DateGenUtil {
@Autowired
//private IDateGen dateGen;
private IDateGen date;
}