Spring Boot注入

0

Spring Boot使用@Autowired注入时,使用类型匹配,然后使用名称匹配。

如果接口和实现都被扫描时,命名一定要注意(注意变量名称变化):

public interface Demo {

	void demo();
	
}
@Service
public class DemoImpl implements Demo {

	@Override
	public void demo() {
	}

}
// 注入成功
@Autowired
private Demo demo;

@Autowired
private Demo demoImpl;

@Autowired
@Qualifier(value = "demo")
private Demo demoEx;
	
@Autowired
@Qualifier(value = "demoImpl")
private Demo demoEx;
	
// 注入失败
@Autowired
private Demo demoEx;

// 异常
required a single bean, but 2 were found:
Consider marking one of the beans as @Primary, updating the consumer to accept multiple beans, or using @Qualifier to identify the bean that should be consumed

接口和实现同时被扫描,第二种方案,使用@Primary注解,可以忽略变量名称:

@Service
@Primary
public class DemoImpl implements Demo {

	@Override
	public void demo() {
	}

}

接口和实现同时被扫描,第三种方案,指定名称:

@Service("demoEx")
public class DemoImpl implements Demo {

	@Override
	public void demo() {
	}

}

接口和实现同时被扫描,第四种方案,注解接口,可以忽略变量名称:

@Service
public interface Demo {

	void demo();
	
}

public class DemoImpl implements Demo {

	@Override
	public void demo() {
	}

}

如果只扫描实现类,不扫描接口,同样可以忽略变量名称。