0

I keep getting this error, and can't figure out why. Yes I know there many people had similar issues, but reading the answers they got, does not solve my problem.

Context initialization failed org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'applicationContextConfig': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.mvc.dao.UserInfoDao com.mvc.config.ApplicationContextConfig.userInfoDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.mvc.dao.UserInfoDao] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}

com.mvc.controller.MainController:

@Controller
public class MainController {
    @RequestMapping(value = { "/", "/welcome" }, method = RequestMethod.GET)
    public String welcomePage(Model model) {
        model.addAttribute("title", "Welcome");
        model.addAttribute("message", "This is welcome page!");
        return "welcomePage";
    }

@RequestMapping(value = "/admin", method = RequestMethod.GET)
public String adminPage(Model model) {
    return "adminPage";
}

@RequestMapping(value = "/login", method = RequestMethod.GET)
public String loginPage(Model model) {

    return "loginPage";
}

@RequestMapping(value = "/logoutSuccessful", method = RequestMethod.GET)
public String logoutSuccessfulPage(Model model) {
    model.addAttribute("title", "Logout");
    return "logoutSuccessfulPage";
}

@RequestMapping(value = "/userInfo", method = RequestMethod.GET)
public String userInfo(Model model, Principal principal) {

    // Sau khi user login thanh cong se co principal
    String userName = principal.getName();

    System.out.println("User Name: " + userName);

    return "userInfoPage";
}

@RequestMapping(value = "/403", method = RequestMethod.GET)
public String accessDenied(Model model, Principal principal) {

    if (principal != null) {
        model.addAttribute("message",
                "Hi " + principal.getName() + "<br> You do not have permission to access this page!");
    } else {
        model.addAttribute("msg", "You do not have permission to access this page!");
    }
    return "403Page";
}
}

com.mvc.dao.UserInfoDao:

public interface UserInfoDao {
public UserInfo findUserInfo(String userName);

// [USER,AMIN,..]
public List<String> getUserRoles(String userName);
}

com.mvc.dao.impl.UserInfoDaoImpl:

public class UserInfoDaoImpl extends JdbcDaoSupport implements UserInfoDao {
@Autowired
public UserInfoDaoImpl(DataSource dataSource) {
    // TODO Auto-generated constructor stub
    this.setDataSource(dataSource);
}

@Override
public UserInfo findUserInfo(String userName) {
    // TODO Auto-generated method stub
    String sql = "Select u.Username,u.Password "//
            + " from Users u where u.Username = ? ";

    Object[] params = new Object[] { userName };
    UserInfoMapper mapper = new UserInfoMapper();
    try {
        UserInfo userInfo = this.getJdbcTemplate().queryForObject(sql, params, mapper);
        return userInfo;
    } catch (EmptyResultDataAccessException e) {
        return null;
    }
}

@Override
public List<String> getUserRoles(String userName) {
    // TODO Auto-generated method stub
    String sql = "Select r.User_Role "//
            + " from User_Roles r where r.Username = ? ";

    Object[] params = new Object[] { userName };

    List<String> roles = this.getJdbcTemplate().queryForList(sql, params, String.class);

    return roles;
}

}

com.mvc.config.ApplicationContextConfig

@Configuration
@ComponentScan("com.mvc.*")

@PropertySource("classpath:datasource-cfg.properties")
public class ApplicationContextConfig {
    @Autowired
    private Environment env;

@Autowired
private UserInfoDao userInfoDAO;

@Bean
public ResourceBundleMessageSource messageSource() {
    ResourceBundleMessageSource rb = new ResourceBundleMessageSource();
    // Load property in message/validator.properties
    rb.setBasenames(new String[] { "messages/validator" });
    return rb;
}

@Bean(name = "viewResolver")
public InternalResourceViewResolver getViewResolver() {
    InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
    viewResolver.setPrefix("/WEB-INF/pages/");
    viewResolver.setSuffix(".jsp");
    return viewResolver;
}

@Bean(name = "dataSource")
public DataSource getDataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();

    // Xem: datasouce-cfg.properties
    dataSource.setDriverClassName(env.getProperty("ds.database-driver"));
    dataSource.setUrl(env.getProperty("ds.url"));
    dataSource.setUsername(env.getProperty("ds.username"));
    dataSource.setPassword(env.getProperty("ds.password"));

    System.out.println("## getDataSource: " + dataSource);

    return dataSource;
}

// Transaction Manager
@Autowired
@Bean(name = "transactionManager")
public DataSourceTransactionManager getTransactionManager(DataSource dataSource) {
    DataSourceTransactionManager transactionManager = new DataSourceTransactionManager(dataSource);

    return transactionManager;
}
}
  • 1
    Make sure all the class/interface within your call chain are annotated, either with specific annotation like ```@RestController, @Service , @Repository``` or with a generic one ```@Component```. In your case, i see UserInfoDao interface is not annotated, try annotating with @Repository. – Dusayanta Prasad Apr 27 '20 at 15:41

3 Answers3

0

Try annotating the UserInfoDaoImpl class with the Spring @Service annotation. This tells spring that the interface has an implementation that it can correctly inject.

See: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Service.html

willm
  • 31
  • 4
0

@ComponentScan looks up bean mark by @Component, @Service, @Controller, etc annotations. Every bean should have one https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/stereotype/Component.html

@Component is a base annotation. @Service, @Controller, @Repository are meta annotations. They add @Component explicitly

Egor
  • 106
  • 4
0

Make sure all the class/interface within your call chain are annotated, either with specific stereotype annotations like @RestController, @Service , @Repository or with a generic one @Component.

Some Good Practices to follow :
The annotations should serve a semantical meaning also.
Means, a controller should be annotated with @RestController.
A Service class should be annotated with @Service and, a DAO Class shall be annotated with @Repository.

In your case, i see UserInfoDaoImpl class is not annotated, try annotating with @Repository, as you don't have a service class, either you can add a service class or just skip @Service annotation.

Dusayanta Prasad
  • 349
  • 3
  • 15