从ClassPathXmlApplicationContext切换到MVC Web flavor上下文实现

时间:2016-04-01 05:08:22

标签: java xml spring hibernate spring-mvc

我正在尝试设置Hibernate来运行Spring来管理简单Web应用程序中的事务。我已经阅读了Spring教程和文档,并设法使用和XMLApplicationContext建立一个有效的玩具示例,引用我的bean定义的xml文件。现在,我正在切换到Spring MVC并使用完全相同的代码和bean定义。我已经通过web.xml链接了我的bean声明的xml文件,但是我一直在做一些奇怪的行为。

这里的参考是我的测试示例的粘贴:http://pastebin.com/gRCBhyiT

以下是我的代码的相关部分:

web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

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

applicationContext.xml:

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

    <context:component-scan base-package="my.base.package" />

    <bean id="defaultTemplateResolver"
          class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
        <property name="prefix" value="/WEB-INF/views/" />
        <property name="suffix" value=".html" />
        <property name="templateMode" value="HTML5" />
    </bean>

    <bean id="templateEngine"
          class="org.thymeleaf.spring4.SpringTemplateEngine">
        <property name="templateResolver" ref="defaultTemplateResolver" />
    </bean>

    <bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
        <property name="templateEngine" ref="templateEngine" />
        <property name="order" value="1" />
        <property name="viewNames" value="*.html,*.xhtml" />
    </bean>

    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/time_tracker"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="annotatedClasses">
            <list>
                <value>my.package.TestData</value>
            </list>
        </property>
        <property name="hibernateProperties">
        <props>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
            <prop key="hibernate.current_session_context_class">thread</prop>
            <prop key="hibernate.show_sql">false</prop>
        </props></property></bean>

    <bean id="testDataDAO" class="my.package.HibernateTestDao">
        <property name="sessionFactory" ref="mySessionFactory"/>
    </bean>

</beans>

application.properties:

spring.thymeleaf.prefix=classpath:/views/
spring.thymeleaf.mode=LEGACYHTML5
#spring.mvc.view.suffix = .jsp

spring.datasource.url=jdbc:mysql://localhost:3306/time_tracker
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=root

spring.jpa.database-platform=org.hibernate.dialect.MySQLDialect
spring.jpa.show-sql=false
spring.jpa.hibernate.ddl-auto=create

申请主要:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }
}

MainController.java:

@Controller
public class MainController implements ApplicationContextAware {

    private ApplicationContext context;
    private HibernateTestDao dao;
    private SessionFactory sessionFactory;

    @Override
    public void setApplicationContext(org.springframework.context.ApplicationContext applicationContext) throws BeansException {
        this.context = applicationContext;
    }

    //@Autowired
    public void setDao(HibernateTestDao dao) {
        this.dao = dao;
    }

    @Autowired
    public void setSessionFactory(SessionFactory factory) {
        this.sessionFactory = factory;
    }

    @RequestMapping(value="/test", method= RequestMethod.GET)
    public String test(Model model) {
        model.addAttribute("name", "testing!");

        System.out.println(context.getBeanDefinitionCount());
        List<String> beans = new ArrayList<String>();
        for (String s : context.getBeanDefinitionNames())
            beans.add(s);

        Collections.sort(beans);
        for (String s : beans)
            System.out.println(s);

        //dao.loadEntries();

        return "test";
    }

    @RequestMapping(value="/", method= RequestMethod.GET)
    public String dashboard() {
        return "dashboard";
    }

    @RequestMapping(value="/view", method= RequestMethod.GET)
    public String edit() {
        return "view_as_form";
    }
}

HibernateTestDao.java:

public class HibernateTestDao {

    private SessionFactory sessionFactory;

    public void setSessionFactory(SessionFactory sessionFactory) {
        this.sessionFactory = sessionFactory;
    }

    @SuppressWarnings("unchecked")
    public List<TestData> loadEntries() {

        Session session = this.sessionFactory.getCurrentSession();
        List<TestData> items = session.createQuery("from TestData").list();
        return items;
    }
}

TestData.java:

@Entity
@Table(name="test")
public class TestData {

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

    private String value1;
    private Date value2;

    public Date getValue2() {
        return value2;
    }

    public void setValue2(Date value2) {
        this.value2 = value2;
    }

    public String getValue1() {
        return value1;
    }

    public void setValue1(String value1) {
        this.value1 = value1;
    }

    public int getId() {
        return id;
    }

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

最初在切换后我收到此错误:

DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE.

我通过在application.properties文件中添加字段来解决这个问题。在此之后,我设法通过测试,现在当我尝试将我的SessionFactory bean注入我的测试类时,我得到一个没有这样的bean定义的异常。我一直在阅读尽可能多的文档,但我找不到发生这种情况的原因。

之前的数据源创建异常可能是为什么会发生这种情况的线索?我认为我得到那个错误很奇怪,因为我在bean本身而不是在外部配置中定义了这些信息。是否创建了一个没有所有bean的servlet上下文?是不是正在读取applicationContext.xml? (它似乎被读为templateEngine,当我打印出所有这些时,defaultTemplateResolver bean会出现)

我最终想要弄明白这一点。我们将非常感谢您提供的任何帮助或指导!

0 个答案:

没有答案