0

So, I am pretty new to Spring MVC, and I think I'm having problems with configuration and I'm going crazy.

I've tried the solution here but either I'm unable to make it work or my mistake is something different

The error I'm getting is:

org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'servicioPersonalUrgenciasImplementacion': Unsatisfied dependency expressed through field 'dao'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.modelo.dao.PersonalUrgenciasDAO' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

My components are: Controller. in com.controladores package

@Controller
public class LoginController {
    
    private ServicioPersonalUrgenciasLogin service;

    @Autowired
    public void setServicioPersonalUrgenciasLogin( ServicioPersonalUrgenciasLogin service) {
        this.service = service;
    }
    
    
    @GetMapping("login")
    public String login(Model model) {
        PersonalUrgenciasLogin login = new PersonalUrgenciasLogin();

        //Add customers to the model
        model.addAttribute("login", login);
        
        return "login";
    }
...
}

Service interface and Service implementation, both in com.modelo.servicios

@Service
public interface ServicioPersonalUrgenciasLogin {

    public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException;
    
    public void cambiarContrasenia(String username, String newpwd);
}

@Service
public class ServicioPersonalUrgenciasLoginImplementacion implements ServicioPersonalUrgenciasLogin {

    @Autowired
    private PersonalUrgenciasLoginDAO dao;
    
    @Override
    @Transactional
    public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        return dao.login(username, pwd);
    }

    @Override
    @Transactional
    public void cambiarContrasenia(String username, String newpwd) {
        // I have to implement this, 

    }

}

DAO Interface and Implementation, both in com.modelo.dao package

I know this is not the way to implement a login, but I wanted something fast

public interface PersonalUrgenciasLoginDAO {

    public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException;
    
    public void cambiarContrasenia(String username, String newpwd);
}

@Repository
public class PersonalUrgenciasLoginDAOImplementacion implements PersonalUrgenciasLoginDAO{

    @Autowired
    private SessionFactory factoria;
    
    @Override
    public boolean login(String username, String pwd) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        Session sesion = factoria.getCurrentSession();

        
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        byte[] hashInOne = md5.digest(pwd.getBytes("UTF-8"));
        String hashMD5String = getString(hashInOne);
        
        
        Query<String> query2 = sesion.createQuery(
                "SELECT usuario FROM PersonalUrgencias WHERE contrasenia=: pwd AND usuario =:user", String.class);
        query2.setParameter("user", username);
        query2.setParameter("pwd", hashMD5String);
        List<String> haLogueado = query2.getResultList();
        
        return !haLogueado.isEmpty();
    }

    @Override
    public void cambiarContrasenia(String username, String newpwd) {
        // TODO Auto-generated method stub
        
    }
    
    
    private static String getString( byte[] bytes ) 
    {
      StringBuffer sb = new StringBuffer();
      for( int i=0; i<bytes.length; i++ )     
      {
         byte b = bytes[ i ];
         String hex = Integer.toHexString((int) 0x00FF & b);
         if (hex.length() == 1) 
         {
            sb.append("0");
         }
         sb.append( hex );
      }
      return sb.toString();
    }

My Entity. I know it is not wired, but I don't want it to be

And then, my web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://xmlns.jcp.org/xml/ns/javaee"
    xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
    id="WebApp_ID" version="3.1">
    <display-name>triaje</display-name>

    <absolute-ordering />

    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

And this is my applicationContext.xml I've tried just writting com in <context:component-scan...> too

<?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"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Add support for component scanning -->
    <context:component-scan base-package="com, com.controladores, com.modelo.dao, com.modelo.entidades, com.modelo.servicios" />

    <!-- Add support for conversion, formatting and validation support -->
    <mvc:annotation-driven/>

    <!-- Define Spring MVC view resolver -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/view/" />
        <property name="suffix" value=".jsp" />
    </bean>

    <!-- Step 1: Define Database DataSource / connection pool -->
    <bean id="myDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
          destroy-method="close">
        <property name="driverClass" value="com.mysql.cj.jdbc.Driver" />
        <property name="jdbcUrl" value="jdbc:mysql://localhost:3316/trj?useSSL=false&amp;serverTimezone=UTC" />
        <property name="user" value="root" />
        <property name="password" value="root" /> 

        <!-- these are connection pool properties for C3P0 -->
        <property name="minPoolSize" value="5" />
        <property name="maxPoolSize" value="20" />
        <property name="maxIdleTime" value="30000" />
    </bean>  
    
    <!-- Step 2: Setup Hibernate session factory -->
    <bean id="factoria"
        class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
        <property name="dataSource" ref="myDataSource" />
        <property name="packagesToScan" value="com.modelo.entidades" />
        <property name="hibernateProperties">
           <props>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
           </props>
        </property>
   </bean>    

    <!-- Step 3: Setup Hibernate transaction manager -->
    <bean id="myTransactionManager"
            class="org.springframework.orm.hibernate5.HibernateTransactionManager">
        <property name="sessionFactory" ref="factoria"/>
    </bean>
    
    <!-- Step 4: Enable configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="myTransactionManager" />

    <!--  Add support for reading web resources: css, images, js... -->
    <mvc:resources location="/resources/" mapping="/resources/**"></mvc:resources>
</beans>

I'm both grateful and sorry for anybody who has read through all of this

ColdDevil
  • 23
  • 5
  • you are missing PersonalUrgenciasDAO... where is it? – J Asgarov May 09 '21 at 19:12
  • It is implemented too. I kind of found out what the problem was. Removing all the other services not used because that was my first controller allows it to run. Idk if leaving Services unused is a bad practice, but without them, my app runs. I honestly don't know if something is wrong with my code or something. – ColdDevil May 09 '21 at 21:32
  • Dead (unused code) is definitely bad practice but that won’t stop it from running. Your error message was saying that it couldn’t find PersonalUrgenciasDAO implementation - maybe u forgot @Component maybe placed in some othe package... anyways glad it is working again – J Asgarov May 10 '21 at 04:32
  • I realised I had some services without the `@Service`. But, the problem keeps there when there is unused code. But when I remove those services, it is still there. Hopefully when I implement the controllers left, the problem will fade and it had to do with dead code. Thank you very much :) – ColdDevil May 10 '21 at 07:04
  • @Service is just another name for Component it is only called service for semantic reasons, if you forget to annotate your beans spring won’t know about them – J Asgarov May 10 '21 at 07:07

0 Answers0