Enter image description here I cannot get a Bean from the spring framework. Following is my code:
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="dao" />
<bean id="dao" class="dao.ProduitDaoImpl" init-method="init">
</bean>
</beans>
in the ControleurServlet.java I tried to appeal springContext.getBean() to have the ProduitDaoImpl object that is configured in applicationContext.xml but I got:
org.springframework.beans.factory.NoSuchBeanDefinitionException:
ControleurServlet.java
package web;
@WebServlet(name="cs", urlPatterns={"*.do"}, loadOnStartup = 1)
public class ControleurServlet extends HttpServlet {
@Autowired
private IProduitDao metier;
private static DataSource ds;
@Override
public void init() throws ServletException {
// TODO Auto-generated method stub
//super.init();
//metier = new ProduitDaoImpl();
System.out.println("Bean 'dao' retrieved from Spring context.");
ApplicationContext springContext=WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
System.out.println("ApplicationContext initialized"+springContext);
metier = (IProduitDao)springContext.getBean("dao");
System.out.println("ProduitDaoImp initialized");
try {
// Perform JNDI lookup to obtain DataSource
Context initContext = new InitialContext();
Context envContext = (Context) initContext.lookup("java:/comp/env");
ds = (DataSource) envContext.lookup("jdbc/myoracle");
// Log success message if DataSource lookup is successful
Logger.getLogger(ControleurServlet.class.getName()).info("DataSource lookup successful");
} catch (NamingException e) {
// Log the NamingException if lookup fails
Logger.getLogger(ControleurServlet.class.getName()).log(Level.SEVERE, "NamingException occurred", e);
// Print the exception stack trace for troubleshooting
}
}
}
ProduitDaoImpl.java
package dao;
@ComponentScan
public class ProduitDaoImpl implements IProduitDao {
public void init() {
System.out.println("Initialisation......");
}
}
web.xml
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:**/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>
org. spring framework.web.context.ContextLoaderListener
</listener-class>
</listener>
I expect to have an instance of ProduitDaoImpl