关于配置profile无法自动注入的问题

lee110 2018-05-10 08:55:19
一个接口:
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 怎么自动注入就不行呢?
...全文
709 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
lee110 2018-05-15
  • 打赏
  • 举报
回复
难道没人知道吗?自己顶上去

67,513

社区成员

发帖
与我相关
我的任务
社区描述
J2EE只是Java企业应用。我们需要一个跨J2SE/WEB/EJB的微容器,保护我们的业务核心组件(中间件),以延续它的生命力,而不是依赖J2SE/J2EE版本。
社区管理员
  • Java EE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧