简体   繁体   中英

expected at least 1 bean which qualifies as autowire candidate. Dependency annotations

I am using java based configuration. I have following code setup which showing error.

public class MyWebInitializer implements WebApplicationInitializer {
    public static Logger logger = Logger.getLogger(MyWebInitializer.class);

    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        logger.info("initializing web context");
        AnnotationConfigWebApplicationContext annotationConfigWebApplicationContext = new AnnotationConfigWebApplicationContext();

        annotationConfigWebApplicationContext.register(FrontController.class);

        ServletRegistration.Dynamic dispatcher = servletContext.addServlet("dispatcher",
                new DispatcherServlet(annotationConfigWebApplicationContext));

        dispatcher.setLoadOnStartup(1);
        dispatcher.addMapping("/");

        logger.info("On start up method complete");
    }

}

Front Controller setup:

@Configuration
@EnableWebMvc
@ComponentScan("com.ishwor.crm.controller,com.ishwor.crm.entity,com.ishwor.crm.DAO")
@PropertySource("classpath:hibenrate.properties")
@EnableTransactionManagement
public class FrontController implements WebMvcConfigurer {
    public static Logger logger = Logger.getLogger(FrontController.class);

    @Autowired
    Environment environment;

    @Bean
    InternalResourceViewResolver internalResourceViewResolver() {
        logger.info("inside view resolver function ");
        InternalResourceViewResolver resolver = new InternalResourceViewResolver();
        resolver.setPrefix("/WEB-INF/views/");
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);
        logger.info("View Resolving complete ");
        return resolver;
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        logger.info("Inside static resource handler");
        // for css and js
        registry.addResourceHandler("/resources/**").addResourceLocations("/WEB-INF/resources/")
                .setCacheControl(CacheControl.maxAge(2, TimeUnit.HOURS).cachePublic());
        logger.info("static resource handling complete");
    }

    // hibernate configuration
    @Bean(name = "sessionFactory")
    public LocalSessionFactoryBean sessionBean() {
        logger.info("Creating sesion bean");
        LocalSessionFactoryBean bean = new LocalSessionFactoryBean();

        bean.setDataSource(dataSource());
        bean.setPackagesToScan(
                new String[] { "com.ishwor.crm.entity", "com.ishwor.crm.DAO", "com.ishwor.crm.DAOImpl" });
        bean.setHibernateProperties(hibernateProperties());
        logger.info("Creating sesion bean=== successfull!!!");
        return bean;
    }

    @Bean
    public DataSource dataSource() {

        logger.info("Datasource method invoked");

        DriverManagerDataSource dataSource = new DriverManagerDataSource();
        dataSource.setDriverClassName(environment.getRequiredProperty("jdbc.driverClassName"));
        dataSource.setUsername(environment.getRequiredProperty("jdbc.username"));
        dataSource.setPassword(environment.getRequiredProperty("jdbc.password"));
        dataSource.setUrl(environment.getRequiredProperty("jdbc.url"));

        logger.info("DataSource Invoke complete");

        return dataSource;
    }

    private Properties hibernateProperties() {
        Properties properties = new Properties();
        logger.info("setting properties for hibernated");
        properties.put("hibernate.dialect", environment.getRequiredProperty("hibernate.dialect"));
        properties.put("hibernate.show_sql", environment.getRequiredProperty("hibernate.show_sql"));
        properties.put("hibernate.format_sql", environment.getRequiredProperty("hibernate.format_sql"));
        properties.put("hibernate.hbm2ddl.auto", environment.getRequiredProperty("hibernate.hbm2ddl.auto"));
        logger.info("setting properties completed");
        return properties;
    }

    @Bean
    public HibernateTransactionManager getTransactionManager() {
        HibernateTransactionManager transactionManager = new HibernateTransactionManager();
        transactionManager.setSessionFactory(sessionBean().getObject());
        return transactionManager;
    }

}

Entity Setp:


import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name = "customer")
public class Customer {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id")
    private long id;

    @Column(name = "first_name")
    private String firstName;

    @Column(name = "last_name")
    private String lastName;

    @Column(name = "email")
    private String email;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public Customer() {

    }

    public Customer(String firstName, String lastName, String email) {
        this.firstName = firstName;
        this.lastName = lastName;
        this.email = email;
    }

    @Override
    public String toString() {
        return "Customer [id=" + id + ", firstName=" + firstName + ", lastName=" + lastName + ", email=" + email + "]";
    }

}

DAO Setup:

package com.ishwor.crm.DAO;

import java.util.List;

import com.ishwor.crm.entity.Customer;

public interface CustomerDAO {
    public List<Customer> getCustomer();

}

DAOImpl setup

  package com.ishwor.crm.DAOImpl;
    
    import java.util.List;
    
    import org.hibernate.Session;
    import org.hibernate.SessionFactory;
    import org.hibernate.query.Query;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.stereotype.Repository;
    import org.springframework.transaction.annotation.Transactional;
    
    import com.ishwor.crm.DAO.CustomerDAO;
    import com.ishwor.crm.entity.Customer;
    
    @Repository
    public class CustomerDAOImpl implements CustomerDAO {
        @Autowired
        @Qualifier("sessionFactory")
        private SessionFactory sessionFactory;
    
        public CustomerDAOImpl() {
    
        }
    
        @Override
        @Transactional
        public List<Customer> getCustomer() {
            // get current hibernate Session
            Session currenSession = sessionFactory.getCurrentSession();
            // create Query
            Query<Customer> myQuery = currenSession.createQuery("from customer", Customer.class);
            // execute query and get result
    
            return myQuery.getResultList();
        }
    }

But Using this DAO as Autowired show the Error I have following customerController setup:

 package com.ishwor.crm.controller;
    
    import java.util.List;
    
    import org.apache.log4j.Logger;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.ui.Model;
    import org.springframework.web.bind.annotation.RequestMapping;
    
    import com.ishwor.crm.DAO.CustomerDAO;
    import com.ishwor.crm.entity.Customer;
    
    @Controller()
    @RequestMapping("/customer")
    public class CustomerController {
    
        public static Logger logger = Logger.getLogger(CustomerController.class);
    
        // Autowired customerDAO
        @Autowired
        private CustomerDAO customerDAO;
        
        
        @RequestMapping("/list")
        public String customerHome(Model model) {
            logger.info("customer index metho browsed");
    
            List<Customer> customer = customerDAO.getCustomer();
            
            model.addAttribute("customer", customer);
    
            return "/customer/index";
        }
    }

Note Without autowiring on controller class code working fine. Should I Used the @service annotation using other one more class and interface in order to this work.

Scanning of components failed.

Add com.ishwor.crm.DAOImpl package in @ComponentScan in the code:

@ComponentScan("com.ishwor.crm.controller,com.ishwor.crm.entity,com.ishwor.crm.DAO,com.ishwor.crm.DAOImpl")

Replace CustomerDAOImpl by CustomerDAO in the CustomerController . It will work.

@Autowired
private CustomerDAO customerDAO;

I think Spring defaults to autowiring by name. You either need to rename the Controller's local variable to be "...Impl" or you need to override the default name of the Impl class.

Looks like your customerDaoImpl is not scanned by spring for annotation processing. Check your configuration, @Autowired will automatically resolve by type of bean. So autowiring is correct, its you cofniguration which is not scanning @Repository annotation and therfoe not creatjng its bean

To scan multiple packages, use String array like below:

@ComponentScan({"com.ishwor.crm.controller","com.ishwor.crm.entity","com.ishwor.crm.DAO"})

yes you should try that @Service class whenever you need to cache data its better to cache data in service class last but not the list @Repository @Service @Controller these 3's are specialized @Component if u use them properly its also called 3 tier architecture. if your projects going large then it will help ua lot.business logic should be in the service class.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM