- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我是 spring 和 hibernate 新手,正在尝试创建简单的 web 应用程序。但我被这个错误困扰了好几天。当我尝试运行 junit 测试时,出现此错误。我在这里缺少什么?
Exception encountered during context initialization - cancelling refresh attempt:
org.springframework.beans.factory.UnsatisfiedDependencyException:
Error creating bean with name 'categoryDAO': Unsatisfied dependency expressed through field
'sessionFactory'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException:
No qualifying bean of type 'org.hibernate.SessionFactory' available:
expected at least 1 bean which qualifies as autowire candidate.
Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}
我的实体类Category.java
@Entity
public class Category {
/*
* private fields
*/
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String name;
private String description;
@Column(name = "img_url")
private String imageurl;
@Column(name = "is_active")
private boolean active = true;
/*
* getters and setters
*/
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getImageurl() {
return imageurl;
}
public void setImageurl(String imageurl) {
this.imageurl = imageurl;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
@Override
public String toString() {
return "Category [id=" + id + ", name=" + name + ", description=" + description + ", imageurl=" + imageurl
+ ", active=" + active + "]";
}
}
PageController.java
@Controller
public class PageController {
@Autowired
private CategoryDAO categoryDAO;
@RequestMapping(value = { "/", "/home", "/index" })
public ModelAndView index() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "home");
//passing the list of categories
mv.addObject("categories", categoryDAO.list());
mv.addObject("userClickHome", true);
return mv;
}
@RequestMapping(value = { "/about" })
public ModelAndView about() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "About us");
mv.addObject("userClickAbout", true);
return mv;
}
@RequestMapping(value = { "/contact" })
public ModelAndView contact() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "Contact us");
mv.addObject("userClickContact", true);
return mv;
}
@RequestMapping(value = "/show/all/products")
public ModelAndView showAllProducts() {
ModelAndView mv = new ModelAndView("page");
mv.addObject("title", "All products");
//passing the list of categories
mv.addObject("categories", categoryDAO.list());
mv.addObject("userClickAllProducts", true);
return mv;
}
@RequestMapping(value = "/show/category/{id}/products")
public ModelAndView showCategoryProducts(@PathVariable("id") int id) {
ModelAndView mv = new ModelAndView("page");
// categoryDAO to fetch a single category
Category category = null;
category = categoryDAO.get(id);
mv.addObject("title", category.getName());
//passing the list of categories
mv.addObject("categories", categoryDAO.list());
//passing the list of category object
mv.addObject("category", category);
mv.addObject("userClickCategoryProducts", true);
return mv;
}
}
CategoryDAOimpl.java
@Repository("categoryDAO")
public class CategoryDAOImpl implements CategoryDAO {
@Autowired
private SessionFactory sessionFactory;
private static List<Category> categories = new ArrayList<>();
//private static CategoryDAO categoryDAO;
static {
Category category = new Category();
// first category
category.setId(1);
category.setName("Television");
category.setDescription("This is some description for television");
category.setImageurl("CAT_1.png");
categories.add(category);
// second category
category = new Category();
category.setId(2);
category.setName("Mobile");
category.setDescription("This is some description for mobile");
category.setImageurl("CAT_2.png");
categories.add(category);
// third category
category = new Category();
category.setId(3);
category.setName("laptop");
category.setDescription("This is some description for laptop");
category.setImageurl("CAT_3.png");
categories.add(category);
}
@Override
public List<Category> list() {
// TODO Auto-generated method stub
return categories;
}
@Override
public Category get(int id) {
//ecnhanced for loop
for(Category category : categories) {
if(category.getId() == id) return category;
}
return null;
}
@Override
@Transactional
public boolean add(Category category) {
try {
//add the category to the database table
sessionFactory.getCurrentSession().persist(category);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
界面CategoryDAO.java
@Service
public interface CategoryDAO {
List<Category> list();
Category get(int id);
boolean add(Category category);
}
HibernateConfig.java
@Configuration
@ComponentScan(basePackages = {"net.kzn.shoppingbackend.dao"})
@EnableTransactionManagement
public class HibernateConfig {
// change the below based on the DBMS you choose
private final static String DATABASE_URL = "jdbc:h2:tcp://localhost/~/onlineshopping";
private final static String DATABASE_DRIVER = "org.h2.Driver";
private final static String DATABASE_DIALECT = "org.hibernate.dialect.H2Dialect";
private final static String DATABASE_USERNAME = "sa";
private final static String DATABASE_PASSWORD = "";
// database bean will be available
@Bean
public DataSource getDataSource() {
BasicDataSource dataSource = new BasicDataSource();
// providing the database connection information
dataSource.setDriverClassName(DATABASE_DRIVER);
dataSource.setUrl(DATABASE_URL);
dataSource.setUsername(DATABASE_USERNAME);
dataSource.setPassword(DATABASE_PASSWORD);
return dataSource;
}
// sessionFactory bean will be available
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("net.kzn.shoppingbackend.dto");
return builder.buildSessionFactory();
}
// All the hibernate properties will be returned in this method
private Properties getHibernateProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", DATABASE_DIALECT);
properties.put("hibernate.show_sql", "true");
properties.put("hibernate.format_sql", "true");
return properties;
}
// transactionManager bean
public HibernateTransactionManager geTransactionManager(SessionFactory sessionFactory) {
HibernateTransactionManager transactionManager = new HibernateTransactionManager(sessionFactory);
return transactionManager;
}
}
CategoryTestCase.java
public class CategoryTestCase {
private static AnnotationConfigApplicationContext context;
private static CategoryDAO categoryDAO;
private Category category;
@BeforeClass
public static void init() {
context = new AnnotationConfigApplicationContext();
context.scan("net.kzn.shoppingbackend");
context.refresh();
categoryDAO = (CategoryDAO) context.getBean("categoryDAO");
}
@Test
public void testAddCategory() {
category = new Category();
category.setName("Television");
category.setDescription("This is some description for television");
category.setImageurl("CAT_1.png");
assertEquals("successfully added a category inside the table!", true, categoryDAO.add(category));
}
}
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>net.kzn</groupId>
<artifactId>shoppingbackend</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>shoppingbackend</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.19.RELEASE</spring.version>
<hibernate.version>5.2.7.Final</hibernate.version>
</properties>
<dependencies>
<!-- JUNIT version 4.12 -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- H2 database -->
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>1.4.197</version>
</dependency>
<!-- Hibernate Dependency -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>${hibernate.version}</version>
<exclusions>
<exclusion>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- database connection pooling -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.1.1</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
我遇到了其他类似的问题,但这没有帮助。
最佳答案
经用户确认,
将 @Bean 添加到 SessionFactory 已解决该问题,
// sessionFactory bean will be available
@Bean
public SessionFactory getSessionFactory(DataSource dataSource) {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource);
builder.addProperties(getHibernateProperties());
builder.scanPackages("net.kzn.shoppingbackend.dto");
return builder.buildSessionFactory();
}
关于java - 如何解决这个: Exception encountered during context initialization - cancelling refresh attempt?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52907420/
我正在尝试将 keras.initializers 引入我的网络,following this link : import keras from keras.optimizers import RMS
我正在为程序创建某种前端。为了启动程序,我使用了调用 CreateProcess(),其中接收到一个指向 STARTUPINFO 结构的指针。初始化我曾经做过的结构: STARTUPINFO star
我已经模板化了 gray_code 类,该类旨在存储一些无符号整数,其基础位以格雷码顺序存储。这里是: template struct gray_code { static_assert(st
我已经查看了之前所有与此标题类似的问题,但我找不到解决方案。所有错误都表明我没有初始化 ArrayList。我是否没有像 = new ArrayList 这样初始化 ArrayList? ? impo
当涉及到 Swift 类时,我对必需的初始化器和委托(delegate)的初始化器有点混淆。 正如您在下面的示例代码中所见,NewDog 可以通过两种方式中的一种进行初始化。如您所见,您可以通过在初始
几天来我一直在为一段代码苦苦挣扎。我在运行代码时收到的错误消息是: 错误:数组初始值设定项必须是初始值设定项列表 accountStore(int size = 0):accts(大小){} 这里似乎
我想返回一个数组,因为它是否被覆盖并不重要,我的方法是这样的: double * kryds(double linje_1[], double linje_2[]){ double x = linje
尝试在 C++ 中创建一个简单的 vector 时,出现以下错误: Non-aggregates cannot be initialized with initializer list. 我使用的代码
如何在构造函数中(在堆栈上)存储初始化列表所需的临时状态? 例如,实现这个构造函数…… // configabstraction.h #include class ConfigAbstraction
我正在尝试编写一个 native Node 插件,它枚举 Windows 机器上的所有窗口并将它们的标题数组返回给 JS userland。 但是我被这个错误难住了: C:\Program Files
#include using namespace std; struct TDate { int day, month, year; void Readfromkb() {
我很难弄清楚这段代码为何有效。我不应该收到“数组初始值设定项必须是初始值设定项列表”错误吗? #include class B { public: B() { std::cout << "B C
std::map m = { {"Marc G.", 123}, {"Zulija N.", 456}, {"John D.", 369} }; 在 Xcode 中,我将 C+
为了帮助你明白这一点,我给出了我的代码:(main.cpp),只涉及一个文件。 #include #include using namespace std; class test{ public
这在 VS2018 中有效,但在 2008 中无效,我不确定如何修复它。 #include #include int main() { std::map myMap = {
我有一个类: #include class Object { std::shared_ptr object_ptr; public: Object() {} template
我正在为 POD、STL 和复合类型(如数组)开发小型(漂亮)打印机。在这样做的同时,我也在摆弄初始化列表并遇到以下声明 std::vector arr{ { 10, 11, 12 }, { 20,
我正在使用解析实现模型。 这是我的代码。 import Foundation import UIKit import Parse class User { var objectId : String
我正在观看 Java 内存模型视频演示,作者说与 Lazy Initialization 相比,使用 Static Lazy Initialization 更好,我不清楚他说的是什么想说。 我想接触社
如果您查看 Backbone.js 的源代码,您会看到此模式的多种用途: this.initialize.apply(this, arguments); 例如,这里: var Router =
我是一名优秀的程序员,十分优秀!