Spring构造型似乎不起作用(无法找到bean)

时间:2011-08-26 09:42:50

标签: java spring stereotype

我有一个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"); 
}

}

我正在用这个问题撕掉我的头发!

1 个答案:

答案 0 :(得分:2)

将@Service更改为@Service(“bamService”)或更改`

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

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

并保存你的头发:)