javaspringstereotype

Spring stereotype doesn't appear to work (bean can't be found)


I have an XML configuration as follows:

    <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"/>

And then in those packages I have the following classes:

@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);
}

I am getting no exceptions in the logs when I start the spring application context, yet when I try the following servlet it cannot find any beans, and I get a NoSuchBeanDefinitionException. Any bean I try to access which has been configured in XML seems to work fine:

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"); 
}

}

I am tearing my hair out with this problem!


Solution

  • Change @Service to @Service("bamService") or change `

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

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

    and save your hair :)