Java 至少需要1个符合autowire候选资格的bean。依赖项注释
我正在使用基于java的配置。我有以下显示错误的代码设置Java 至少需要1个符合autowire候选资格的bean。依赖项注释,java,spring,spring-mvc,Java,Spring,Spring Mvc,我正在使用基于java的配置。我有以下显示错误的代码设置 public class MyWebInitializer implements WebApplicationInitializer { public static Logger logger = Logger.getLogger(MyWebInitializer.class); @Override public void onStartup(ServletContext servletContext) thro
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");
}
}
前控制器设置:
@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;
}
}
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";
}
}
实体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设置:
package com.ishwor.crm.DAO;
import java.util.List;
import com.ishwor.crm.entity.Customer;
public interface CustomerDAO {
public List<Customer> getCustomer();
}
package com.ishwor.crm.DAO;
导入java.util.List;
导入com.ishwor.crm.entity.Customer;
公共接口客户道{
公共列表getCustomer();
}
DAOImpl设置
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();
}
}
package com.ishwor.crm.DAOImpl;
导入java.util.List;
导入org.hibernate.Session;
导入org.hibernate.SessionFactory;
导入org.hibernate.query.query;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.beans.factory.annotation.Qualifier;
导入org.springframework.stereotype.Repository;
导入org.springframework.transaction.annotation.Transactional;
导入com.ishwor.crm.DAO.CustomerDAO;
导入com.ishwor.crm.entity.Customer;
@存储库
公共类CustomerDAOImpl实现CustomerDAO{
@自动连线
@限定符(“会话工厂”)
私人会话工厂会话工厂;
公共客户DaoImpl(){
}
@凌驾
@交易的
公共列表getCustomer(){
//获取当前休眠会话
会话currenSession=sessionFactory.getCurrentSession();
//创建查询
Query myQuery=currenSession.createQuery(“来自客户”,customer.class);
//执行查询并获取结果
返回myQuery.getResultList();
}
}
但使用此DAO作为自动连线显示错误,我有以下customerController设置:
@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;
}
}
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";
}
}
package com.ishwor.crm.controller;
导入java.util.List;
导入org.apache.log4j.Logger;
导入org.springframework.beans.factory.annotation.Autowired;
导入org.springframework.stereotype.Controller;
导入org.springframework.ui.Model;
导入org.springframework.web.bind.annotation.RequestMapping;
导入com.ishwor.crm.DAO.CustomerDAO;
导入com.ishwor.crm.entity.Customer;
@控制器()
@请求映射(“/customer”)
公共类客户控制器{
publicstaticlogger=Logger.getLogger(CustomerController.class);
//自动连线客户道
@自动连线
私人客户道客户道;
@请求映射(“/list”)
公共字符串customerHome(模型){
logger.info(“浏览的客户索引方法”);
List customer=customerDAO.getCustomer();
model.addAttribute(“客户”,客户);
返回“/客户/索引”;
}
}
注意没有控制器类代码上的自动接线,工作正常。
为了完成这项工作,我是否应该使用@service注释并使用另一个类和接口。我认为Spring默认按名称自动连接。您需要将控制器的局部变量重命名为“…Impl”,或者需要覆盖Impl类的默认名称。看起来您的customerDaoImpl没有被spring扫描以进行注释处理。检查您的配置,@Autowired将根据bean的类型自动解析。因此,自动连接是正确的,它是您的联合配置,不扫描@Repository注释,也不创建它的bean要扫描多个包,请使用如下字符串数组:
@ComponentScan({"com.ishwor.crm.controller","com.ishwor.crm.entity","com.ishwor.crm.DAO"})
是的,当你需要缓存数据时,你应该尝试@Service类,最好是最后一个缓存服务类中的数据,而不是列表@Repository@Service@Controller。如果你正确使用它们,这3个是专门的@Component,也称为3层架构。如果你的项目规模很大,那么它将对你有很大帮助。业务逻辑应该在服务类中。扫描组件失败 在代码中的
@ComponentScan
中添加com.ishwor.crm.DAOImpl
包:
@ComponentScan("com.ishwor.crm.controller,com.ishwor.crm.entity,com.ishwor.crm.DAO,com.ishwor.crm.DAOImpl")
将CustomerDAOImpl
替换为CustomerDAO
中的CustomerDAO
。它会起作用的
@Autowired
private CustomerDAO customerDAO;
谢谢你的回复。我尝试了这两种方法,但都不起作用,仍然是相同的错误。现在我正在使用这个
@ComponentScan(“com.ishwor.crm.controller,com.ishwor.crm.entity,com.ishwor.crm.DAO,com.ishwor.crm.daimpl”)
现在的错误代码是'Bean named'customerDAOImpl'应该是'com.ishwor.crm.DAOImpl.customerDAOImpl'类型,但实际上是'com.sun.proxy.$Proxy130'`现在我正在使用这个@ComponentScan({“com.ishwor.crm.controller,com.ishwor.crm.entity,com.ishwor.crm.DAOImpl,com.ishwor.crm.DAOImpl”))
现在就使用它:@ComponentScan({“com.ishwor.crm.controller,com.ishwor.crm.entity,com.ishwor.crm.DAO,com.ishwor.crm.DAOImpl”})
错误代码为:名为“customerDAOImpl”的Bean应为“com.ishwor.crm.DAOImpl.customerDAOImpl”类型,但实际为“com.sun.proxy.$Proxy165”类型。
请在问题中添加异常日志。