一个接口:
public interface Speakable {
public void say();
}
两个实现类
@Component
@Profile("china")
public class Chinese implements Speakable {
@Override
public void say() {
System.out.println("说中文");
}
}
@Component
@Profile("english")
public class English implements Speakable {
@Override
public void say() {
System.out.println("说英文");
}
}
一个Person类:
@Component
public class Person {
@Autowired
private Speakable speak;
public void say(){
speak.say();
}
}
测试代码如下:
public static void main(String[] args) {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("bean-config.xml");
context.getEnvironment().setActiveProfiles("china");
context.refresh();
Person p = context.getBean("person", Person.class);
p.say();
}
运行提示错误:Error creating bean with name 'person': Unsatisfied dependency expressed through field 'speak'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jku.bean.Speakable' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
Exception in thread "main" org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'person': Unsatisfied dependency expressed through field 'speak'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.jku.bean.Speakable' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
只要把autowired配置成required=false就可以运行成功
但无法理解的是 既然不同的profile可以自动生成不同的bean 怎么自动注入就不行呢?