1

我有一个如下的 XML 配置:

    <beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:aop="http://www.springframework.org/schema/aop"
   xmlns:tx="http://www.springframework.org/schema/tx"
   xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="
    http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
    http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">

   <context:component-scan base-package="bamAddressbook.service"/>
   <context:component-scan base-package="bamAddressbook.repository.addressbook"/>

然后在这些包中我有以下类:

@Service
public class BamService {
@Autowired
BamAddressbookDAO addressbookDao;

@Transactional
public void businessLogic() {
    Addressbook addressbook = new Addressbook();
    addressbookDao.makePeristent(addressbook);
}

}

@Repository
public class AddressbookDAOHibernate extends HibernateGenericDAO<Addressbook> implements BamAddressbookDAO {
@Override
public Addressbook getFromUser(User user) {
    throw new UnsupportedOperationException("Not supported yet.");
}

}

public interface BamAddressbookDAO extends InterfaceGenericDAO<Addressbook>{
   public Addressbook getFromUser(User user);
}

.

public interface InterfaceGenericDAO<T> {
   public T get(Long databaseID);
   public List<T> getAll();
   public void makePeristent(T entity);
   public void makeTransient(T entity);
}

当我启动 spring 应用程序上下文时,日志中没有异常,但是当我尝试以下 servlet 时,它找不到任何 bean,并且我得到了 NoSuchBeanDefinitionException。我尝试访问的任何已在 XML 中配置的 bean 似乎都可以正常工作:

public class BamServlet extends HttpServlet {

@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(
                                                                    req.getSession().getServletContext());

    BamService bean = (BamService) context.getBean("bamService"); 
}

}

我正在为这个问题撕毁我的头发!

4

1 回答 1

2

将 @Service 更改为 @Service("bamService") 或更改 `

BamService bean = (BamService) context.getBean("bamService");`到

BamService bean = context.getBean(BamService.class);

并保存你的头发:)

于 2011-08-26T10:55:47.260 回答