2012-08-10 91 views
0

我是Spring 3的新手,它提供了一堆注释,它避免了声明式方法。 基于注释和声明式方法之间的区别究竟是什么?注释是否有缺点?Spring声明与注释

+0

可能是http://stackoverflow.com/questions/182393/xml-configuration-versus-annotation-based-configuration?rq=1 – heldt 2012-08-10 06:19:26

回答

1

使用注释是一种方法使用声明的方式,而不是使用programmpatic方法,包括在你的方法额外的Java代码:

声明方式:

@Transactional 
public void transferMoney(Long debitorId, Long creditorId, BigDecimal amount) { 
    Account debitor = accountDAO.findById(debitorId); 
    Account creditor = accountDAO.findById(creditorId); 
    creditor.add(amount); 
    debitor.remove(amount); 
} 

编程方法:

public void transferMoney(Long debitorId, Long creditorId, BigDecimal amount) { 
    transactionTemplate.execute(new TransactionCallbackWithoutResult() { 
     @Override 
     protected void doInTransactionWithoutResult(TransactionStatus status) { 
      Account debitor = accountDAO.findById(debitorId); 
      Account creditor = accountDAO.findById(creditorId); 
      creditor.add(amount); 
      debitor.remove(amount); 
     } 
    }); 
} 
+0

不应该第一个是'注解方法',而声明式方法==通过上下文配置XML声明? – 2012-08-10 08:25:36

+0

你给他们你想要的名字。我的观点是使用注释仍然是一种声明方式。您使用注释在源代码中声明,而不是在外部XML文件中声明它,但它仍然是声明性的,因为它使方法的代码保持原样,完全集中在业务代码上。 – 2012-08-10 08:33:22

+0

你是对的,它们都是自然界的声明。我可能会在原始问题的推动下发表评论:声明与注释?在这种情况下,正确的问题应该是:'在XML中声明而在注释中声明'。 – 2012-08-10 09:05:40