No qualifying bean of type is defined: expected single matching bean but found 2

最近在Spring的注解中,尝试获取一个Bean出现了如题所示的错误。

NoUniqueBeanDefinitionException: No qualifying bean of type is defined: expected single matching bean but found 2:sysRoleManage, sysRoleManageImpl 

我有2个类,1个是接口:

public interface SysRoleManager{
  //............
}

 另一个是该接口的实现类:

@Compnent
public class SysRoleManagerImpl implements SysRoleManager{
  //............实现抽象方法
}

 尝试获取bean的时候:

ApplicationContext ctx = WebApplicationContextUtils.getWebApplicationContext(ServletContext);

SysRoleManager manager = ctx.getBean(SysRoleManager.class);
System.out.println(manager);

 得到如题所示的错误。

解决办法,在实现类上的注解要更详细些,改成:

@Service("sysRoleManager")
public class SysRoleManagerImpl implements SysRoleManager{
  //............实现抽象方法
}

 这样,就能解决问题,打印出:

com.xx.xxx.SysRoleManagerImpl@179e64

说明获取到了实现类。

或者可以不用通过Spring上下文去获取,直接透过注解的方式:

@Autowire
@Qualifier("sysRoleManager ")
private SysRoleManager manager;

 

假如有多个实现类实现同一接口,需要在每个实现类上注解不同的@Service("name"),name为不同值。

顺便补充下hibernate的一个异常:例如,

org.hibernate.HibernateException: identifier of an instance 

of org.cometd.hibernate.User altered from 12 to null。

那是因为:

1)你是否在注解的时候把非主键的字段配置了@NaturalId等主键生成策略;

2)是否在一个事务中更新了主键,而主键是不能被更新的。

 

猜你喜欢

转载自raising.iteye.com/blog/2286927