Java 为什么我得到这个Spring异常没有定义类型的限定bean预期是单个匹配bean,但找到了2?
我正在学习Spring Core认证,我有以下疑问: 当我执行JUnit测试方法时,我获得了此错误消息,这是提供的用户指南所期望的,然后解释如何修复它:Java 为什么我得到这个Spring异常没有定义类型的限定bean预期是单个匹配bean,但找到了2?,java,spring,Java,Spring,我正在学习Spring Core认证,我有以下疑问: 当我执行JUnit测试方法时,我获得了此错误消息,这是提供的用户指南所期望的,然后解释如何修复它: Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [rewards.internal.account.AccountRepository] is defined: expected si
Caused by: org.springframework.beans.factory.NoUniqueBeanDefinitionException: No qualifying bean of type [rewards.internal.account.AccountRepository] is defined: expected single matching bean but found 2: stubAccountRepository,jdbcAccountRepository
at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:970)
at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:858)
at org.springframework.beans.factory.support.ConstructorResolver.resolveAutowiredArgument(ConstructorResolver.java:811)
at org.springframework.beans.factory.support.ConstructorResolver.createArgumentArray(ConstructorResolver.java:739)
... 43 more
据我所知,这是因为Spring发现了多个相同类型的bean:stubAccountRepository和jdbcAccountRepository:
这是StubAccountRepository类:
}
上一条错误消息的确切来源是什么
我认为这是在应用程序启动时发生的配置问题。对吗
我认为这是因为这两个类都是用@Repository StubAccountRepository和jdbAccountRepository注释的,并且实现了AccountRepository接口,所以Spring无法知道哪个类用作AccountRepository的已实现存储库
我的推理是正确的还是遗漏了什么?关于这种情况,你能再给我解释一下吗
Tnx好吧,Maksym已经告诉过你了,但为了让你更清楚,我会尽量更详细
您有两个“AccountRepository”接口的实现:StubAccountRepository和JdbcAccountRepository。当您对“AccountRepository”类型使用@Autowired注释时,您只需告诉Spring执行“autowire by type”。所以Spring检查应该自动连接的字段的类型,并尝试定位该类型的单个bean,就像调用ApplicationContext.GetBeanCountRepository.class一样。由于无法找到该类型的单个bean,ApplicationContext无法启动。Yep,正确,您应该指定bean名称并使用qualifier注释;
/**
* A dummy account repository implementation. Has a single Account
* "Keith and Keri Donald" with two beneficiaries "Annabelle" (50% allocation)
* and "Corgan" (50% allocation) associated with credit card "1234123412341234".
*
* Stubs facilitate unit testing. An object needing an AccountRepository can
* work with this stub and not have to bring in expensive and/or complex
* dependencies such as a Database. Simple unit tests can then verify object
* behavior by considering the state of this stub.
*/
@Repository
public class StubAccountRepository implements AccountRepository {
private Logger logger = Logger.getLogger(StubAccountRepository.class);
private Map<String, Account> accountsByCreditCard = new HashMap<String, Account>();
/**
* Creates a single test account with two beneficiaries. Also logs creation
* so we know which repository we are using.
*/
public StubAccountRepository() {
logger.info("Creating " + getClass().getSimpleName());
Account account = new Account("123456789", "Keith and Keri Donald");
account.addBeneficiary("Annabelle", Percentage.valueOf("50%"));
account.addBeneficiary("Corgan", Percentage.valueOf("50%"));
accountsByCreditCard.put("1234123412341234", account);
}
public Account findByCreditCard(String creditCardNumber) {
Account account = accountsByCreditCard.get(creditCardNumber);
if (account == null) {
throw new EmptyResultDataAccessException(1);
}
return account;
}
public void updateBeneficiaries(Account account) {
// nothing to do, everything is in memory
}
}
private Logger logger = Logger.getLogger(JdbcAccountRepository.class);
private DataSource dataSource;
/**
* Constructor logs creation so we know which repository we are using.
*/
public JdbcAccountRepository() {
logger.info("Creating " + getClass().getSimpleName());
}
/**
* Sets the data source this repository will use to load accounts.
* @param dataSource the data source
*/
@Autowired
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
public Account findByCreditCard(String creditCardNumber) {
String sql = "select a.ID as ID, a.NUMBER as ACCOUNT_NUMBER, a.NAME as ACCOUNT_NAME, c.NUMBER as CREDIT_CARD_NUMBER, b.NAME as BENEFICIARY_NAME, b.ALLOCATION_PERCENTAGE as BENEFICIARY_ALLOCATION_PERCENTAGE, b.SAVINGS as BENEFICIARY_SAVINGS from T_ACCOUNT a, T_ACCOUNT_BENEFICIARY b, T_ACCOUNT_CREDIT_CARD c where ID = b.ACCOUNT_ID and ID = c.ACCOUNT_ID and c.NUMBER = ?";
Account account = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = dataSource.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, creditCardNumber);
rs = ps.executeQuery();
account = mapAccount(rs);
} catch (SQLException e) {
throw new RuntimeException("SQL exception occurred finding by credit card number", e);
} finally {
if (rs != null) {
try {
// Close to prevent database cursor exhaustion
rs.close();
} catch (SQLException ex) {
}
}
if (ps != null) {
try {
// Close to prevent database cursor exhaustion
ps.close();
} catch (SQLException ex) {
}
}
if (conn != null) {
try {
// Close to prevent database connection exhaustion
conn.close();
} catch (SQLException ex) {
}
}
}
return account;
}
public void updateBeneficiaries(Account account) {
String sql = "update T_ACCOUNT_BENEFICIARY SET SAVINGS = ? where ACCOUNT_ID = ? and NAME = ?";
Connection conn = null;
PreparedStatement ps = null;
try {
conn = dataSource.getConnection();
ps = conn.prepareStatement(sql);
for (Beneficiary beneficiary : account.getBeneficiaries()) {
ps.setBigDecimal(1, beneficiary.getSavings().asBigDecimal());
ps.setLong(2, account.getEntityId());
ps.setString(3, beneficiary.getName());
ps.executeUpdate();
}
} catch (SQLException e) {
throw new RuntimeException("SQL exception occurred updating beneficiary savings", e);
} finally {
if (ps != null) {
try {
// Close to prevent database cursor exhaustion
ps.close();
} catch (SQLException ex) {
}
}
if (conn != null) {
try {
// Close to prevent database connection exhaustion
conn.close();
} catch (SQLException ex) {
}
}
}
}
/**
* Map the rows returned from the join of T_ACCOUNT and T_ACCOUNT_BENEFICIARY to an fully-reconstituted Account
* aggregate.
* @param rs the set of rows returned from the query
* @return the mapped Account aggregate
* @throws SQLException an exception occurred extracting data from the result set
*/
private Account mapAccount(ResultSet rs) throws SQLException {
Account account = null;
while (rs.next()) {
if (account == null) {
String number = rs.getString("ACCOUNT_NUMBER");
String name = rs.getString("ACCOUNT_NAME");
account = new Account(number, name);
// set internal entity identifier (primary key)
account.setEntityId(rs.getLong("ID"));
}
account.restoreBeneficiary(mapBeneficiary(rs));
}
if (account == null) {
// no rows returned - throw an empty result exception
throw new EmptyResultDataAccessException(1);
}
return account;
}
/**
* Maps the beneficiary columns in a single row to an AllocatedBeneficiary object.
* @param rs the result set with its cursor positioned at the current row
* @return an allocated beneficiary
* @throws SQLException an exception occurred extracting data from the result set
*/
private Beneficiary mapBeneficiary(ResultSet rs) throws SQLException {
String name = rs.getString("BENEFICIARY_NAME");
MonetaryAmount savings = MonetaryAmount.valueOf(rs.getString("BENEFICIARY_SAVINGS"));
Percentage allocationPercentage = Percentage.valueOf(rs.getString("BENEFICIARY_ALLOCATION_PERCENTAGE"));
return new Beneficiary(name, allocationPercentage, savings);
}